Reputation: 444
I'm currently working on a notes app in React and I've built a 404 page and now if I go to a route that doesn't exist it shows a 404 page
for example, if I go to the route /get-the-note/
I get a 404 page.
But the problem is that I have a route:
<Route exact path="/single-note/:id" component={Singlenote}></Route>
which needs an id and if I put the correct id like I have a note with id no 2
and if I go to the route /single-note/2
it works but if I put an id that doesn't exist like if I put an id 120
which doesn't exist and I go to the route /single-note/120
I get a plain page instead of a 404 page. I want it show the 404 page even if the id is incorrect
here is my app.js file:
import "./App.css";
import Homepage from "./components/homepage.component";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Singlenote from "./components/singlenote.component";
import PageNotFound from "./components/404_page";
function App() {
return (
<Router>
<Switch>
<Route exact path="/" component={Homepage} />
<Route exact path="/single-note/:id" component={Singlenote}></Route>
<Route path="*"><PageNotFound /></Route>
</Switch>
</Router>
);
}
export default App;
and here is my 404 page:
import React from 'react'
const PageNotFound = () => {
return (
<div id="wrapper">
<img src="https://i.imgur.com/qIufhof.png" />
<div id="info">
<h3>This page could not be found</h3>
</div>
</div >
)
}
export default PageNotFound
Upvotes: 0
Views: 241
Reputation: 498
The approach I suggest for this is by modifying your Singlenote
component, with a useEffect
hook, that checks if the id provided exists or not, only once on mount (useEffect(() => { code for check }, []);
). In the event that the id does not exist, you can redirect the execution to your 404 component, by using history (e.g. history.push('*')
, where * is used as the path to redirect to, you could use something else that is not covered in the routes, so it will go to 404).
I have to add that this is not a good approach, I would personally go with a notification or other indicator displayed when accessing your Singlenote
component with an id that does not exist (again with useEffect), which informs the user that no results or data were found for the given id.
Upvotes: 0
Reputation: 169298
The router has no way of knowing which IDs do and do not exist.
It's up to your Singlenote
to render 404 content if there is no such ID.
For the last route in the Switch, you don't need the path at all, by the way.
<Route component={PageNotFound} />
Upvotes: 1