I'm building a web app with three main parts: The actual website, an admin part and a user part. For each part, I want a different layout wrapper.
This is my code right now:
Website wrapper
const Website = () => (
<React.Fragment>
<NavigationBar />
<main>
<div className="container">
<Switch>
<Route exact path='/' component={Home}/>
<Route exact path='/login' component={Login}/>
</Switch>
</div>
</main>
<FooterBar />
</React.Fragment>
);
User wrapper
const User = () => (
<React.Fragment>
<UserSideBar />
<main>
<div className="container">
<Switch>
<Route exact path='/u/dashboard' component={UDashboard}/>
<Route exact path='/u/account' component={UAccount}/>
</Switch>
</div>
</main>
</React.Fragment>
);
Admin wrapper
const Admin = () => (
<React.Fragment>
<main>
<div className="container">
<Switch>
<Route exact path='/a/dashboard' component={ADashboard}/>
<Route exact path='/a/payments' component={APayments}/>
<Route exact path='/a/account' component={AAccount}/>
</Switch>
</div>
</main>
</React.Fragment>
);
Router
const Router = () => (
<BrowserRouter>
<Switch>
<Route path="/u" component={User} />
<Route path="/a" component={Admin} />
<Route path="/" component={Website} />
<Redirect from="*" to="/" />
</Switch>
</BrowserRouter>
);
It's all working fine but if an url is not matching any of the routes, it's not redirecting to '/'
. How can I achieve this?
Firstly wrap all the content of your page inside the return function inside the . Next, create the induvial routes inside the component. For each route, we have the path and the element props, these tell the path on the address bar and the component to be rendered out respectively.
Two ways to handle redirecting on a user event such as create, update and delete with React Router.
You could just make a reusable component NoMatch and included at the bottom of your Switch
.
For example:
<Switch>
<Route exact path='/a/dashboard' component={ADashboard}/>
<Route exact path='/a/payments' component={APayments}/>
<Route exact path='/a/account' component={AAccount}/>
<Route component={Notfound} />
</Switch>
Make sure to put it at the very end So, if no other route was matched, that one would be displayed.
Or you can make a simple custom function which you can reuse depending on your needs:
You could do this if the undefined path is not clear:
const createRedirect = to => () => <Redirect to={to} />
// ...
<Route path="/*" component={createRedirect('/foo')} />
To implement a redirect
fallback in a switch
, you need to do:
<Switch>
<Route path="/foo" component={Bar}/>
<Route path="/bar" component={Baz}/>
<Route render={() => <Redirect to="/foo"/>}/>
</Switch>
Or you can take the longer approach and make it programmatically redirect. Here is a reference of a reusable component, or at least reusable logic that you could implement to your needs: Reference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With