How to make 404 pages with ReactJS

Tram Ho

  • Page 404 is also known as the page not found and it usually pops up when the user enters the wrong link or the link is not available. In this case to create the cohesive UI, we need to show them a 404 page instead of a blank page and let them know that the page they’re looking for is not.
  • How do I create a custom 404 in React?
  • To understand how to create it, we first need to make sure that we understand how Routing works in React. The React Router is what we’ll use to create the SPA
  • In React and React Router, we are in SPA (Single Page Apps), so of course there will be no “404” page – but instead a component. The component will need to show up if a router is not recognized.
  • Thankfully, this is very simple and easy in React Router!
  • Inside the <Switch /> component from the React Router, we can declare a <Route /> at the end of the route declaration.
  • This means that if the above routers are not suitable, the only possible solution is to create a router that doesn’t really exist.
  • To help us change dynamic data, we use React Router. This feature conditionally displays certain elements to display depending on the routet being used in the URL (/, / login, / register, etc.).
  • To use the router, you have to install it first using npm: npm install react-router-dom
  • The usage is that we import the components we need to use into our code:

  • How can we create a 404 component? In your component mail, create a new file called NotFound.js and add the following code:

  • After creating a not found component, make sure you import the file into our routers configuration.

  • The switch ensures that only one of the appropriate routers is visible at a time. It will only show the first router that matches the url and no other routers. For this reason, we have to put the final 404 component
  • And a little more style will dc the 404 page to my liking
  • demo page 404: https://codesandbox.io/s/pedantic-mcnulty-iktm8?file=/src/NotFound.js
Share the news now

Source : Viblo