Reputation: 3562
So I have a React application with some routes on it using react-router. While messing around with the different routes I accidentally miss typed a route.
My issue is that even though I miss typed the route, my application still rendered the application just fine; no 404 error thrown. My App.js file is defined as such:
class App extends Component {
render() {
return (
<div>
<BrowserRouter>
<div>
<MenuBar /> //SIMPLIFIED FOR POST
<SearchBar path="/search" exact/>
</div>
</BrowserRouter>
</div>
);
}
}
I'm assuming since my MenuBar component is rendered to every route because there's no specified route, that is the reason there is no 404 error
My other components that DO have exact routes specified, they should be the only routes allowed to be typed in, otherwise I want to render a 404 component to the screen
Question(s): How do I display a 404 error to every route that isn't specified? I cant figure out a solution since MenuBar has to be on every route. Let's say someone tells me I should only render menu bar to the specified routes, but still how can I find out or know when an invalid route is typed in? I'm guessing I need some sort of middleware to check?
Upvotes: 0
Views: 268
Reputation: 1624
You can do this by wrapping your routes within the Switch
component then you simply add this :
<Route component={Component} />
Notice how this route don't have the 'path' prop. Now this route will renders when a 'no match' occurs.
You can see a working example in the official react-router docs
Upvotes: 1