React Router is the routing library for React. It is a collection of routing components. It used to navigate the website from one page to another page.
Many latest websites using this SPAs (Single Page Applications) technology, and in this technology, react-router conditionally render components for all different pages without refreshing the whole page.
To use react-router, you have to install React-Router with the help of NPM (Node Packages Manager) or Yarn.
Note: If your machine don’t have NPM installed then read article here. In this article I have explained how you can setup enviorment for reactjs application.
Let’s start with install React-Router.
To install it run this command in your terminal.
npm install react-router-dom
It will install the required dependency to use navigate the website. You can check your package.json file. It will show all dependency that you have installed.
Uses of React-Router
Next, you have to create new component file OR can test in your src/App.js file. In this file, import the BrowserRouter, Route, and Switch from
Let’s understand with examples, how we can use it?
In the example, let’s suppose we have a website and navigation like
These navigation pages handled by the router, and when you click on these links (
<Link>) then the router will render the certain component based on the URL (
Check the below examples of react-router navigation.
Example 1: Basic Routing
In the above example we used
<Router> (refer to
All Routes will render inside the Router, and
<Link> is used for making hyperlinks same as we do with anchor tag (<a>). We can also use this instead of
<Switch> is used for making conditioning between Links and Route and show the certain component based on the requested URL as a result.
This is the basic example of routing navigation with React-Router.
Let’s see another example of Nested Routing:
Example 2: Nested Routing
Nested Routing means navigation has a submenu under the main menu. As we declared above navigation link
But now, suppose the services menu has more menus under this, as called submenu like
So, how we will make this navigation and render the component based on the submenu with parameter ID?
Look at the example for nested routing.
In the above example, we imported 2 more library from
useRouteMatch hook gives the access to match with the current URL, and get URL property from its object. And useParams used to return the value from URL parameters.
Note: There is more attributes for navigation link like exact, strict, isActiveetc. You can check here.
So, in this article, we learned how to install React-Router and Programmatically navigate using React-Router.
Hope you understand this code. If you have any query please comment out, I’ll help you with that.