How to use Routing in the React
How to use routing in the React
Before starting for the procedure for routing. Firstly, we discuss are React Router and its components.
React Router is a library used to create the routing in React application. It helps us to navigate between the components in the application and also allows us to change the URL and sync in UI with it. It is mainly used for a single-page web application. The main role of Routing to display multiple views in the application such as Facebook, Instagram use this technology.
To install the React Router, run the command at the prompt: npm install react-router-dom –save
React Router contains 3 different packages in it such as react-router, react-router-native, and react-router-dom.
There are Components in React Router such as:
- BrowserRouter: It is used for sync in with the UI with the URL. As the parent component, they store all of the other components.
- Route: It is a condition in that when the path matches the URL it renders the components based on the specific path.
- Link: It is used to connect the different route by creating the links and navigate for the application.
- Switch: If the path matched, it used to render the components else it returns “not found” component.
Steps for routing in the React Application:
- First to create a project using create-react-app and after that install the React Router by changing the project directory.
i.e. create-react-app router
npm install react-router-dom –-save
where the router is a project name. Creating the app then open the project folder in the code editor.
- Open App.js add the code given below and also create a folder name component inside the src folder and create 3 js file i.e. home.js, about.js, and contact.js.
- Now add the react-router component to the application:
- Add the browser router to your App.js for storing all other components. It will be a parent component
- Now create the links to component given by us such as home, about, and contact and by using these we can navigate it to describe the location of the components.
- Add the route component for creating the link between UI and URL.
- Now wraps all the routes inside the switch to render a single component.
Finally, this is how we use routing in react that helps us to navigate the components with each other by clicking on the links of components and it always syncs in the UL component with URL.