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:
How to setup React Router v6 ?
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:
Table of Content
- Approach to setup React Router in Application
- Steps to set up React Router
- Implementation of React Router v6
- Nested Routes
- useNavigate()
- DynamicRoutes
- createRoutesFromElements
Contact Us