Reputation: 1268
I have a component which takes in similar props to the standard react-router Route
and returns a route. This returned route has a render prop which just passes through the component but adds a nav component. This custom NavRoute
does not work with the react-router Switch
component, as when I use the custom component inside the switch along with a catch-all 404 page, the page always shows.
How can I make the 404 component only show if none of the other routes match the url?
NavRoute
const NavRoute = ({ exact, path, component: Component }) => {
return (
<Route exact={exact} path={path} render={(props) => (
<div style={styleSideNav}>
<Nav />
<Component {...props} />
</div>
)}/>
);
});
Usage
<Switch>
<NavRoute exact path="/" component={Home} />
<NavRoute exact path="/about" component={About} />
<Route path="/" component={Page404} />
</Switch>
EDIT: Codesandbox of full example: https://codesandbox.io/s/react-router-stack-overflow-5jcum Url of codesandobx: https://5jcum.csb.app/invite/abc
Upvotes: 4
Views: 2111
Reputation: 505
Switch only works with the first level of components directly under it. It can't traverse the entire tree.
https://github.com/ReactTraining/react-router/issues/5785#issuecomment-351067856
To fix that, we can pass array of routes instead of routes wrapped in fragment. I have made the changes and updated in codesandbox.
https://codesandbox.io/s/react-router-stack-overflow-hu62w?file=/src/App.js
Upvotes: 3