How to Navigate Between Pages React
In the below tutorial, you will learn step-by-step how to navigate between pages in react js.
Steps:
1-Install react-router dom package.
2-Wrap your entire application with the BrowserRouter component.
3-Set the path for each component using Route and Routes component.
4-Use the Link component to navigate between pages.
1- Install react-router dom package
In your terminal put the following :
npm i react-router-dom
2- Wrap your entire application with the BrowserRouter component
Open the index.js file in your application and wrap it with BrowserRouter as it cleared in the image below :
Notice that we import the BrowserRouter component at the top of the page then we call inside the render to wrap the App component.
3- Set the path for each component using Route and Routes component
Now in our App.js file, we will decide component paths using Route and Routes components as cleared in the image below :
As in the preview section, we import our Route&Routes component at the top, Routes component will play the wrapper rule where the Route component will be called inside for each path we need to set.
4- Use the Link component to navigate between pages
Finally, we should replace our linkable element with the Link component as cleared in the image below :
We shouldn’t miss importing the Link component at the top to be able to use it inside the nav element.