React JS - Routing

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.










Open App.js and under <BrowserRouter> wrapper we can call Navbar component.







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 :




Params / Dynamic Routing - Passing Dynamic Parameters in URL

We can pass dynamic parameters in URL. In the following example, peter and john are dynamic parameters.
abc.com/user/peter
abc.com/user/john


Comments