React router is used to navigate from one component to another. It provides different elements through which the components can be wrapped out. Also, you can render the component separately based on the route. In this post, we will talk about React Router DOM. Recently the React Router has upgraded to React Router V6. This is the latest update and it has totally enhanced from its previous version. Here, you will see lots of new breaking changes inside the routing. We will see all these things one by one in-depth.
For this, we will start with a new installation of React app. But, before going with a demo, let’s see what’s new in React Router 6.
What’s New in React Router V6
Here, we will discuss the important features one by one.
- In the new version,
<Switch>
is replaced with<Routes>
. - For rendering a component through route, the component has been replaced with the element.
- Now, you can create Nested routes in a parent-child route manner.
- A useNavigate hook has been introduced to redirect to a specific URL.
- You can read URL params using the useParams hook.
- The index route has been added for rendering the default component.
We will see all these features by their implementation in this post.
How to use Redux, React Redux in React JS with Example
Prerequisites
If you are an absolute beginner in React and you started directly with React Router V6 then this is fine. But, I assume you are familiar with the basics of React.
Create React App
Open the terminal and create a new app by hitting the below command.
npx create-react-app react-router-app
Once you have created the app. Let’s open it in the editor. Run it and check whether the installation has been completed successfully.
npm start
Switch to the browser and check the application result.
Now, we are good to go for the installation of React Router V6 in this app.
Install React Router DOM V6 in React Js
Stay ahead to the terminal and hit the below command. It will take a couple of seconds to install the library.
npm i react-router-dom
After successful installation, you can check it in the package.json file.
Now, let’s create a few components in our app to implement the routing using React Router V6.
Create Components in React Js
For the simplicity of the application, I am going to create separate components folder and inside that will create a couple of components.
- Header.jsx
- Home.jsx
- About.jsx
- Contact.jsx
Apart from these components, we have the default App.js component. In the App component, I have imported a few objects from react-router-dom.
import { BrowserRouter, Routes, Route } from 'react-router-dom';
Let’s see these imports in the App component.
import React from 'react';
import { Home } from './components/Home';
import { About } from './components/About';
import { Contact } from './components/Contact';
import { Header } from './components/Header';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import './App.css';
export const App = () => {
return (
<div className="App">
<BrowserRouter>
<Header />
<Routes>
<Route path='/' element={<Home />} />
<Route path='/about' element={<About />} />
<Route path='/contact' element={<Contact />} />
</Routes>
</BrowserRouter>
</div>
);
}
In the above component, you can see a few things.
- The Route is wrapped inside the
<Routes></Routes>
. - For rendering the component, we used the element object.
The App.js component is rendered in the index.js file.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import { App } from './App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
reportWebVitals();
When you run the app, you will have the below results.
You can switch to the other routes using the link. It will render the component respectively.
Same for the next link. On click on Contact, it opened the Contact component.
Next, we will see the Nested Routes features in React Routing V6.
Nested Routes in React JS
This is an amazing feature inside React Routing. You can create a route inside another route. This is called a nested route. For a better understanding let’s create a few more components.
- HomeFirstChild.jsx
- HomeSecondChild.jsx
- AboutCompany.jsx
- Mission.jsx
- Vision.jsx
Also, I have updated the navbar using the Bootstrap component. Hence, the Header.jsx component has changed now.
import React from "react";
import { Link } from "react-router-dom";
export const Header = () => {
return (
<nav className="navbar navbar-expand-md navbar-dark bg-dark">
<div className="container">
<Link to={'/home'} className="navbar-brand">Programming Fields</Link>
<button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarNavDropdown">
<ul className="navbar-nav m-auto">
<li className="nav-item dropdown">
<Link to={'/home'} className="nav-link dropdown-toggle" id="navbarDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Home
</Link>
<ul className="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<li><Link to={'/home/child'} className="dropdown-item">Child 1</Link></li>
<li><Link to={'/home/child2'} className="dropdown-item">Child 2</Link></li>
</ul>
</li>
<li className="nav-item dropdown">
<Link to={'/about'} className="nav-link dropdown-toggle" id="navbarDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false">
About Us
</Link>
<ul className="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<li><Link to={'/about'} className="dropdown-item">About Us</Link></li>
<li><Link to={'/about/company'} className="dropdown-item">Company</Link></li>
<li><Link to={'/about/vision'} className="dropdown-item">Vision</Link></li>
<li><Link to={'/about/mission'} className="dropdown-item">Mission</Link></li>
</ul>
</li>
<li className="nav-item">
<Link to={'/contact'} className="nav-link">Contact Us</Link>
</li>
</ul>
</div>
</div>
</nav>
);
}
Now, you can render the child element inside the parent. For this, there is a new element introduced in React Router V6.
Outlet in React Router V6
This element is used as a placeholder. The <Outlet>
allows you to render components to its child routes. So, all the child routes belonging to the home route will be rendered using Outlet in the parent (Home.jsx) component.
Let’s see using the example. Take a look at the below code.
import React from "react";
import { Outlet } from "react-router-dom";
export const Home = () => {
return (
<div className="container text-center py-5">
<h3> Home component </h3>
<Outlet />
</div>
);
}
This is our main home component. Here, the <Outlet /> component has created a placeholder.
Now, let’s come to the App.js component for creating the nested route.
import React from 'react';
import { Home } from './components/Home';
import { About } from './components/About';
import { Contact } from './components/Contact';
import { Header } from './components/Header';
import { HomeFirstChild } from './components/HomeFirstChild';
import { HomeSecondChild } from './components/HomeSecondChild';
import { Vision } from './components/Vision';
import { Mission } from './components/Mission';
import { AboutCompany } from './components/AboutCompany';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import './App.css';
export const App = () => {
return (
<div className="App">
<BrowserRouter>
<Header />
<Routes>
<Route path='/home' element={<Home />}>
<Route path='child' element={<HomeFirstChild />} />
<Route path='child2' element={<HomeSecondChild />} />
</Route>
<Route exact path='/about' element={<About />}>
<Route path='company' element={<AboutCompany />} />
<Route path='mission' element={<Mission />} />
<Route path='vision' element={<Vision />} />
</Route>
<Route path='/contact' element={<Contact />} />
</Routes>
</BrowserRouter>
</div>
);
}
Take a look at the result to see the magic. By default at “/home” we have the home component.
For simplicity, I have created a dropdown menu having two submenus in the Home link. We have two submenus – Child 1 and Child 2.
On click on the child menu, the child component is called in the same (parent) component.
Similarly, after clicking on the second submenu, the second child component will be rendered.
Similarly, you can add more child routes and render the child component.
Next, we will see the usage of useNavigate hook.
useNavigate Hook in React
This hook is introduced to set the custom redirection on any URL. If you already worked on React Router V5 then you would see the useHistory hook. This is the replacement in the React Router 6.
You can import it in the same way as you do for other packages.
import { useNavigate } from "react-router-dom"
Let’s implement it with the example.
import React from "react";
import { useNavigate } from "react-router-dom";
export const HomeFirstChild = () => {
const navigate = useNavigate();
return (
<>
<p> Home child 1 component</p>
<button className="btn btn-primary" onClick={() => navigate('/home')}>Redirect to Home </button>
</>
)
}
The above component will generate the result as shown below.
useParams Hook in React JS
This hook is used to get the parameter from the browser through the URL. Suppose, if you want to get a record of a single student then that time it will be helpful.
You will have to import it first as shown below.
import React from "react";
import { useParams } from "react-router-dom";
export const HomeSecondChild = () => {
const param = useParams();
return (
<>
<p> Home child 2 component</p>
<p> Param : {param.id}</p>
</>
)
}
Next, you will have to define a route to navigate to a component. I will keep it inside the Home route group.
<Route path='child2/:id' element={<HomeSecondChild />} />
After adding the above route, the App.js component will look like this.
import React from 'react';
import { Home } from './components/Home';
import { About } from './components/About';
import { Contact } from './components/Contact';
import { Header } from './components/Header';
import { HomeFirstChild } from './components/HomeFirstChild';
import { HomeSecondChild } from './components/HomeSecondChild';
import { Vision } from './components/Vision';
import { Mission } from './components/Mission';
import { AboutCompany } from './components/AboutCompany';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import './App.css';
export const App = () => {
return (
<div className="App">
<BrowserRouter>
<Header />
<Routes>
<Route path='/home' element={<Home />}>
<Route path='child' element={<HomeFirstChild />} />
<Route path='child2' element={<HomeSecondChild />} />
<Route path='child2/:id' element={<HomeSecondChild />} />
</Route>
<Route path='/about' element={<About />}>
<Route path='company' element={<AboutCompany />} />
<Route path='mission' element={<Mission />} />
<Route path='vision' element={<Vision />} />
</Route>
<Route path='/contact' element={<Contact />} />
</Routes>
</BrowserRouter>
</div>
);
}
Check in the result. Pass any parameter after the URL. Whatever you will pass in the browser URL, it will be captured by this hook.
Conclusion
We have seen the implementation of Routing in React JS using React Router V6. There are lots of new functionalities have added with this hook. We haven’t covered all things in this single post. I tried to give a look at the major features which are mostly in use while creating a React application. That’s it for this post. Thank you.
Leave a Reply