How to setup React Router v6 ?
Last Updated : 02 Aug, 2024
React Router is an amazing library that was created by Remix. The purpose of React Router is to enable Client-Side routing in the React application, that is, by using React Router we can create different routes in our React app and can easily navigate to different pages without even reloading the page.
Client-side routing, facilitated by React Router, enables changing routes without page reloads, creating single-page applications (SPAs). React Router efficiently manages what is displayed on each route, making it a powerful and user-friendly library for seamless navigation in React applications.
We will discuss the following setup approach and different methods of React Router v6 in this article:
Approach to setup React Router in Application
- NavBar.js: Utilizes the
Link
tag instead of an anchor tag for navigation without page reloads. Ensures the website remains a single-page application. - index.js: Uses
createBrowserRouter
to establish routes: "/" (Home), "/home" (About), "/contact" (Contact). Wraps components needing routing in RouterProvider
with the created router. - App.js: Renders NavBar and the
Outlet
component provided by React Router. Outlet
dynamically displays content based on the current route.
Steps to set up React Router
Step 1: Create a react project folder, open the terminal, and write the following command.
# Run this to use npm
npx create-react-app foldername
# Or run this to use yarn
yarn create react-app foldername
Step 2: Navigate to the root directory of your project using the following command.
cd foldername
Step 3: Now, install the React Router library
npm install react-router-dom
or
yarn add react-router-dom
Project Structure
Project StructureThe updated dependencies in package.json file will look like:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
"react-router-dom": "^6.22.0"
}
Implementation of React Router v6:
Example: Below is the code to create the navbar and routes.
CSS /* App.css */ nav { background-color: #333; padding: 10px; } ul { list-style-type: none; margin: 0; padding: 0; } li { display: inline; margin-right: 20px; } a { text-decoration: none; color: white; } a:hover { color: lightgray; }
JavaScript // NavBar.js import { Link } from 'react-router-dom'; const Navbar = () => { return ( <nav> <ul> <li><Link to="/">Home</Link></li> <li><Link to="/about">About</Link></li> <li><Link to="/contact">Contact</Link></li> </ul> </nav> ); } export default Navbar;
JavaScript // index.js import React from 'react' import ReactDOM from 'react-dom/client' import { RouterProvider, createBrowserRouter } from 'react-router-dom' import App from './App' import Home from './Home' import About from './About' import Contact from './Contact' const router = createBrowserRouter([ { path: '/', element: <App />, children: [ { path: '/', element: <Home />, }, { path: '/about', element: <About />, }, { path: '/contact', element: <Contact />, }, ] } ]); ReactDOM.createRoot(document.getElementById('root')).render( <RouterProvider router={router}> <App /> </RouterProvider> )
JavaScript // App.js import { Outlet } from 'react-router-dom'; import './App.css' import NavBar from "./NavBar"; const App = () => { return ( <> <NavBar /> <Outlet /> </> ); } export default App;
JavaScript // Home.js import React from 'react' const Home = () => { return ( <div>Home</div> ) } export default Home
JavaScript // About.js import React from 'react' const About = () => { return ( <div>About</div> ) } export default About
JavaScript // Contact.js import React from 'react' const Contact = () => { return ( <div>Contact</div> ) } export default Contact
Start your application using the following command.
npm start
Output:
Nested Routes:
Nested routes means routes within routes. For example, the About page can have two links, one link for About company and one link for About founder of the company.
We will have to create routes something like these.
"/about/about-founder"
"/about/about-company"
This is what nested routes are. So creating nested routes is very simple, as you have already created a route for about, you have to add children array to it.
Example 2: Below is an example of nested routes.
JavaScript // About.js import { Outlet, useNavigate } from "react-router-dom" const About = () => { const navigate = useNavigate(); return ( <div> <button onClick={() => navigate("about-founder")}>About - Founder</button> <button onClick={() => navigate("about-company")}>About - Company</button> <Outlet /> </div> ) } export default About
JavaScript // index.js import React from 'react' import ReactDOM from 'react-dom/client' import App from './App' import { RouterProvider, createBrowserRouter } from 'react-router-dom' import Home from './Home' import About from './About' import Contact from './Contact' import Founder from './Founder' import Company from './Company' const router = createBrowserRouter([ { path: '/', element: <App />, children: [ { path: '/', element: <Home />, }, { path: '/about', element: <About />, children: [ { path: "about-founder", element: <Founder /> }, { path: "about-company", element: <Company /> } ] }, { path: '/contact', element: <Contact />, }, ] } ]); ReactDOM.createRoot(document.getElementById('root')).render( <React.StrictMode> <RouterProvider router={router}> <App /> </RouterProvider> </React.StrictMode> )
JavaScript import React from 'react' const Founder = () => { return ( <div>Founder</div> ) } export default Founder
JavaScript import React from 'react' const Company = () => { return ( <div>Comapny</div> ) } export default Company
Output:
OutputuseNavigate():
This is a hook given by React Router. useNavigate returns a function, and using this function we can navigate anywhere. You just need to enter the path where you want to navigate. That's all there was to nested routes, now you can create routes at any depth. Now let's see how to create dynamic routes.
DynamicRoutes:
Let us first understand what dynamic routes are. Dynamic route means the route that we did not know before. They are created dynamically based on any variable or parameter and are non-static and numbers can reach thousands and millions.
for example, this youtube video link:
https://youtube.com/watch/[some video id]
Now this video ID will be different for every video. So such routes are dynamic routes.
To set up dynamic routes, let's take an example. Suppose there are many contacts in the contact page and each contact has a unique ID. We will just use this unique ID and create pages for all contacts with just one route.
We can write a path like this
path: "/contact/:id"
Example 3: Look at the below code for a better understanding
JavaScript // ContactCard.js import { useParams } from "react-router-dom" const ContactCard = () => { const { id } = useParams(); return ( <h1>Contact id: {id}</h1> ) } export default ContactCard
JavaScript // index.js import React from 'react' import ReactDOM from 'react-dom/client' import App from './App' import { RouterProvider, createBrowserRouter } from 'react-router-dom' import Home from './Home' import About from './About' import Contact from './Contact' import Founder from './Founder' import Company from './Company' import ContactCard from './ContactCard' const router = createBrowserRouter([ { path: '/', element: <App />, children: [ { path: '/', element: <Home />, }, { path: '/about', element: <About />, children: [ { path: "about-founder", element: <Founder /> }, { path: "about-company", element: <Company /> } ] }, { path: '/contact', element: <Contact />, }, { path: "/contact/:id", element: <ContactCard /> } ] } ]); ReactDOM.createRoot(document.getElementById('root')).render( <React.StrictMode> <RouterProvider router={router}> <App /> </RouterProvider> </React.StrictMode> )
Output:
createRoutesFromElements:
If you do not like the syntax to create routes from these objects then we can also use a different syntax. To do this, we will call another function in createBrowserRouter which is createRoutesFromElements and in this function, we will set up the routes.
import {
RouterProvider,
createBrowserRouter,
createRoutesFromElements,
Route,
} from "react-router-dom";
const router = createBrowserRouter(
createRoutesFromElements(
<Route path="/" element={<App />}>
<Route path="/" element={<Home />} />
\\Other Route
</Route>
)
);
Similar Reads
Migrate to React Router v6
React Router v6 brings significant changes and improvements over its predecessor, offering a more intuitive API and better performance. Migrating to React Router v6 might seem daunting, but with proper guidance, the transition can be smooth and beneficial for your React applications. Enhancements in
3 min read
How to setup 404 page in React Routing?
When you're building a React app with routing, it's important to handle cases where users land on a page that doesn't exist. A 404 page is a good way to inform users that the page theyâre looking for cannot be found. Prerequisites:NPM & Node JSReact JSReact-router-domApproach to Set Up a 404 Pag
4 min read
React Router Tutorial
React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL. With React Router, you can create a single-page application (SPA) with multiple "pages"
3 min read
useRoutes Hook in React Router
React Router is a library that is used for handling navigation and routing in React applications. It provides a way to navigate between different components or pages while maintaining a single-page application (SPA) structure. One of the key features is the useRoutes hook. It allows you to define ro
4 min read
How to setup ReactJs with Vite ?
Vite is a fast and modern build tool for creating web applications. It increases the development process by providing faster build times and better performance. Some of the benefits of using React with Vite are mentioned below: Fast updates without page reloads.Faster and smaller production builds.A
3 min read
React Router V5 vs V6
React Router is widely appreciated in React apps for handling routing and navigation. It provides a way to configure routes. Show components based on the current URL. The newest release, React Router v6 introduces changes and improvements compared to the version of React Router v5. This article will
7 min read
React-Router Hooks
React-Router is a popular React library that is heavily used for client-side routing and offers single-page routing. It provides various Component APIs( like Route, Link, Switch, etc.) that you can use in your React application to render different components based on the URL pathnames on a single pa
11 min read
React JS Types of Routers
When creating a React application, managing navigation between different views or pages is important. React Router is the standard library for routing in React, enabling seamless navigation while maintaining the Single Page Application (SPA) behaviour. What is React Router?React Router is a declarat
10 min read
React Router vs. React Router DOM
Routing is a fundamental part of any web application. It allows users to move between pages or views. smoothly in traditional web development Routing involves mapping URLs to specific content or views on the server. These are the following topics that we are going to discuss: Table of Content What i
4 min read
How to use TypeScript with React?
TypeScript enhances JavaScript by adding strict type definitions, making your code more robust and maintainable. ReactJS, a popular library for building user interfaces, pairs excellently with TypeScript to create clean, efficient, and scalable codebases. Combining TypeScript with React offers a pow
3 min read