Reputation: 885
I'm using React Router to manage the URLs of my webapp. This is what I have so far in Routes.js
:
const Routes = () => {
return (
<React.Fragment>
<Navbar />
<Switch>
<Route exact path="/inicio" component={Home} />
<Route path="/productos" component={Products} />
<Route path="/la-empresa" component={LaEmpresa} />
<Route path="/contacto" component={Contact} />
<Route path="/servicios" component={Servicios} />
<Route path="/prensa" component={Prensa} />
</Switch>
<WhatsappBtn />
<Footer />
</React.Fragment>
);
};
As you can see, I'm rendering the navbar, footer and a whatsapp floating button in every page, and inside those goes the content. I thought that this was awesome, since I'm not loading those three every time the user goes to a different page, but I'm coming across this issue: When I visit a URL that does not correspond to any of the paths, I get those components anyways (which makes sense). I would like to display a 404 page instead.
How is this possible whithout sacrificing the performance?
Upvotes: 2
Views: 1103
Reputation: 465
You can add a catch-all path at the end of your routes in order to render a 404 component for any unknown paths:
...
<Route exact path="/prensa" component={Prensa} />
<Route path="*" component={My404Component} />
It must be last, otherwise any route defined after it won't be considered
Upvotes: 1
Reputation: 61
You can use simple Route without the path like this:
<Route component={404Page} />
This will show 404Page on every path which you dont specify.
Upvotes: 2
Reputation: 5015
my suggestion is to add a AppContainer
which would render the passed component together with the NavBar, WhatsappBtn and Footer.
Then you can add a path="/"
which would be the error page.
Performance is not an issue since your component will only be rendered if the path matches! And also only the first one to match will be rendered
Upvotes: 1
Reputation: 314
you can simply add another <Route />
below the last route like this
<Route path='*' component={() => <h2>404 NOT FOUND</h2>} />
Upvotes: 3
Reputation: 7642
you can do this:
<Route path="*" component={ErrorPage} />
and then set exact
on all other routes like so:
<Route exact path="/some/other/path" component={OtherComponent} />
Upvotes: 2