Routing is a process to navigate from one component to another component without reloading entire page.
React Router 6 is the latest version.
Official Website : www.reactrouter.com
Installing Router
Open terminal and write following command :
npm i react-router-dom
Now, we will create a new folder component/ inside src/ and create two components : Home.js and About.js
Open App.js and create Route for each component inside <BrowserRouter> and <Routes> wrapper.
In above code, we have created Route for Home and About respectively.
Create Navigation Links & Common Navigation Component
Create a New Component Navbar.js and create Link for both components. This component file will be common component and is re-usable.
Create 404 & Redirecting
In React, if a user tries to open a page which does not exist, then we can redirect the user to 404.
For this, we need to create a new component Page404.js :
To redirect to Page404 :
We can also redirect to specific component, if page is not found.
In the below example, we are redirecting to Home Page/Component, if page is not found :
Comments
Post a Comment