Hello All,
In previous article we have learnt that, how to handle the routing in React JS.
React Js 2 : Adding routing to React JS application
But What happens when we update URL and enter
For Example:
http://localhost:3000/about
Above request works without any issue
If we change the request about2 instead about the we do not get any output.
http://localhost:3000/about2
output:
We could see the warning in console. Go to browser -> Right Click --> InspectIt is not good practice to display the black screen, instead we can show the 404 page.
How to do?
Its very simple, Just we need to Set the path to * It will catch-all undefined URLs. This is great for a 404 error page.
Implementation:
Lets continue from Previous article.
Step 1:
- Clone the source code from GitHub Path
- Open source code in VSCode
- Then run the npm install command in terminal(this will restore all the dependency)
- Run the application npm start
Step 2:
Create component called 404.js in component folder and add below content in it.
404.js:
const PageNotFound =()=>{ return ( <h1>404 - Requested Page Not found</h1> ) } export default PageNotFound
Go to App.js, import the PageNotFound file and add the Route.
import { BrowserRouter as Router,Link, Route, Routes } from 'react-router-dom' import Home from './components/Home' import AboutUs from './components/AboutUs' import ContactUs from './components/ContactUs' import PageNotFound from './components/404' function App () { return <Router> <h1>Welcome to React Router Example</h1> <ul> <li><Link to="/">Home</Link></li> <li><Link to="/about">About US</Link></li> <li><Link to="/contact">Contact US</Link></li> </ul> <Routes> <Route exact path='/' element={<Home/>}></Route> <Route path='/about' element={<AboutUs/>}></Route> <Route path='/contact' element={<ContactUs/>}></Route> <Route path='*' element={<PageNotFound/>}></Route> </Routes> </Router> } export default App
We have done, now lets run the application.
Thats it for this article, i hope you enjoyed this.
As usual, Please let us know in case any concerns with the help of comment section.
See you in next article, until then take care.