Wednesday, June 4, 2025

Nested Route in React Router With Example

In this post we'll see how to configure nested routes or child routes in React Router.

Nested routes in React

You can nest a route inside another route which establishes a parent route-child route relationship.

<Route path="parent" element ={<Parent />}>
    <Route path="child" element = {<Child/>}/>
</Route >

With this kind of nested route, child URL path is relative to the path to parent which means this route configuration creates both /parent and /parent/child URLs.

With nested routes you can also control the rendering of the child routes which can be rendered with in the context of parent using the Outlet component.

import { Outlet } from "react-router";
export default function Parent() {
  return (
    <div>
      <h1>Parent</h1>
      {/* will render <Child/> */}
      <Outlet />
    </div>
  );
}

Example of nested route can be seen in this post- Using NavLink in React Router where route configuration is as shown here-

<Route path="/" element {<NavigationNavLink />}>
  <Route index element={<Home />} />
  <Route path="about" element={<About />} />
</Route>

With this configuration "/" and "/about" are nested paths with in the root URL.

Dynamic nested route in React

You can also nest a dynamic route so that dynamic path segment can be mapped to a route. For example, if you have a product page that shows product names and clicking on any product displays the details of that product. This means you need to add the id part as dynamic path segment so that any path in this format /product/{ID} is mapped to the route.

<Routes>
  <Route path="/" element={<NavigationNavLink />}>
    <Route index element={<Home />} />
    <Route path="product" element={<RouteProduct />}> 
      <Route path=":productId" element={<RouteProductDetails />} /> 
    </Route>
    <Route path="about" element={<About />} />
  </Route>
</Routes>

As you can see here this particular nested route-

<Route path="product" element={<RouteProduct />}> 
  <Route path=":productId" element={<RouteProductDetails />} /> 
</Route>

Will map to any path like- /product/101, /product/23 and so on.

That's all for this topic Nested Route in React Router With Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Index Route in React Router
  2. Routing in React With Example
  3. React Declarative Approach
  4. React Virtual DOM

You may also like-

  1. React create-react-app Project Structure
  2. JavaScript Rest Parameter
  3. ArrayList in Java With Examples
  4. Count Number of Times Each Character Appears in a String Java Program
  5. Java Stream API Interview Questions And Answers
  6. What is Client Side Routing in Angular

Index Route in React Router

In this post we'll see what are Index routes in React Router.

You can think of index routes as nested routes that don't have their own path. Consider this route definition which was used in post- Using NavLink in React Router.

<Route path="/" element={<NavigationNavLink />}>
  <Route path="/" element={<Home />} />
  <Route path="about" element={<About />} />
</Route>

Requirement here is; when the user accesses the root URL, navigation menu should be rendered (NavigationNavLink component) and Home component should also be rendered. That is why path="/" is used in both the routes.

In such scenario child route can be defined as an index route making it a default child route which should be rendered into their parent's <Outlet/> when the path for the parent route is accessed.

If we take the route definition as stated above, child route can be configured with the index prop to make it an index route.

<Route path="/" element={<NavigationNavLink />}>
  <Route index element={<Home />} />
  <Route path="about" element={<About />} />
</Route>

Using index with createBrowserRouter

If you are using createBrowserRouter to configure routes then index routes are defined by setting index: true on a route object without a path

export const route = createBrowserRouter([
      {path: "/", element: <NavigationNavLink />,
      children: [
         {index: true, element: <Home /> },
         {path: "/about", element: <About />}
      ]
      }
])

That's all for this topic Index Route in React Router. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Routing in React With Example
  2. Link in React Router With Example

You may also like-

  1. React Declarative Approach
  2. React Virtual DOM
  3. React create-react-app Project Structure
  4. JavaScript Rest Parameter
  5. ArrayList in Java With Examples
  6. Count Number of Times Each Character Appears in a String Java Program
  7. Java Stream API Interview Questions And Answers
  8. What is Client Side Routing in Angular

Tuesday, June 3, 2025

Using NavLink in React Router

In the post Link in React Router With Example we saw how to create a navigation menu or link one page to another using Link in React Router. In this post we'll see how we can use NavLink in React Router to create a Navigation Menu.

NavLink in React Router

With NavLink you can create active links which means highlighting the currently selected menu item. A link can be in active or pending state (pending state is available only with framework and data modes).

Accessing link state

In NavLink there are className and style props, using these props you can access isActive and isPending states and style them.

Using className

The className prop takes a function with an object as parameter that can be destructured to get isActive and isPending properties. These properties are of type Boolean. If current link is active then isActive has the value true otherwise value is false.

Function returns a css class name that should be added for styling.

<NavLink
  to="/about"
  className={({ isActive, isPending }) =>
    isPending ? "pending" : isActive ? "active" : ""
  }
>
  About
</NavLink>

As you can see in the above code, if isActive returns true then active is returned as the className. So, you can write your own CSS with active class styling.

Using style prop

The style prop takes a function with an object as parameter that can be destructured to get isActive and isPending properties. These properties are of type Boolean. If current link is active then isActive has the value true otherwise value is false.

Function returns style for the state.

<NavLink to="/about" style={({ isActive, isPending }) => ({
  color:
    isActive ? "red" :
    isPending ? "blue" : "black"
})}>
  About
</NavLink>

Navlink navigation menu example

1. CSS

This is the CSS class used for styling the links.

src\components\routes\navigation.css

#menu a:link,
#menu a:visited {
    color: gray;
}
#menu a:hover {
    color: white;
}
#menu a.active {
    color: #7FFFD4;
}

#menu a {
    text-decoration: none;
}

#menu ul {
    gap: 1rem;
}

2. Components

Components that are mapped to the routes

src\components\routes\Home.js

import { Link } from "react-router";
const Home = () => {
    return (
    <>
        <h2>This is home page</h2>
        <Link to="/about">About</Link>
    </>
    )
}
export default Home;

src\components\routes\About.js

const About = () => {
    return <h2>This is about page</h2>
}

export default About;

3. Navigation component

Menu for navigation is created as a separate file, uses Bootstrap 5 for styling.

src\components\routes\NavigationNavLink.js

import { NavLink, Outlet } from "react-router";
import "./navigation.css";
const NavigationNavLink = () => {
    const style = (({ isActive, isPending }) => 
        isPending ? "pending" : isActive ? "active" : ""
    );
    return(
        <>
            <nav id="menu" className="navbar navbar-expand-lg bg-dark navbar-dark">
                <div className="container-fluid">
                    <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarMenu" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                        <span className="navbar-toggler-icon"></span>
                    </button>

                    <div className="collapse navbar-collapse" id="navbarMenu">
                        <ul className="navbar-nav">
                            <li>
                                <NavLink className={style} to="/">
                                    Home
                                </NavLink>
                            </li>
                            <li>
                                <NavLink className={style} to="/about">
                                    About
                                </NavLink>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
        </>
    );
}

export default NavigationNavLink;

App.js

Since <NavLink/> cannot be rendered outside <BrowserRouter/> so you should add the Navigation component wrapped with in the BrowserRouter.

import { BrowserRouter, Route, Routes } from 'react-router';
import About from './components/routes/About';
import Home from './components/routes/Home';
import NavigationNavLink from './components/routes/NavigationNavLink';
function App() {
  return (
    <>
      <BrowserRouter >
       <NavigationNavLink />
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="about" element={<About />} />
        </Routes>
      </BrowserRouter>
    </>
  );
}

export default App;

With these changes if you access the about page- http://localhost:3000/about

NavLink in React Router

Navigation menu with child routes and Outlet

In the above example we saw how to create a navigation menu with NavLink, it works fine but the recommended way to do it is to create routes as child routes of the navigation route.

App.js

That's where routing is configured.

import { BrowserRouter, Route, Routes } from 'react-router';
import About from './components/routes/About';
import Home from './components/routes/Home';
import NavigationNavLink from './components/routes/NavigationNavLink';
function App() {
  return (
    <>
      <BrowserRouter >
        <Routes>
          <Route path="/" element={<NavigationNavLink />}>
            <Route path="/" element={<Home />} />
            <Route path="about" element={<About />} />
          </Route>
        </Routes>
      </BrowserRouter>
    </>
  );
}

export default App;

As you can see Navigation component acts as a parent route and other components are specified as the child routes.

Navigation component

In the Navigation component add the Outlet so that the matching child route of a parent route is rendered at the place specified by Outlet.

src\components\routes\NavigationNavLink.js

import { NavLink, Outlet } from "react-router";
import "./navigation.css";
const NavigationNavLink = () => {
    const style = (({ isActive, isPending }) => 
        isPending ? "pending" : isActive ? "active" : ""
    );
    return(
        <>
            <nav id="menu" className="navbar navbar-expand-lg bg-dark navbar-dark">
                <div className="container-fluid">
                    <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarMenu" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                        <span className="navbar-toggler-icon"></span>
                    </button>

                    <div className="collapse navbar-collapse" id="navbarMenu">
                        <ul className="navbar-nav">
                            <li>
                                <NavLink className={style} to="/">
                                    Home
                                </NavLink>
                            </li>
                            <li>
                                <NavLink className={style} to="/about">
                                    About
                                </NavLink>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
            <Outlet />
        </>
    );
}

export default NavigationNavLink;

That's all for this topic Using NavLink in React Router. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. React Declarative Approach
  2. React Virtual DOM
  3. React create-react-app Project Structure
  4. JavaScript Rest Parameter

You may also like-

  1. ArrayList in Java With Examples
  2. Count Number of Times Each Character Appears in a String Java Program
  3. Java Stream API Interview Questions And Answers
  4. What is Client Side Routing in Angular

Link in React Router With Example

In the post Routing in React With Example we saw how to configure routes with the help of an example. The problem with that example was to manually change the path. In a real application there will be links and navigation menu to move around different web pages. So, you need to link to your routes from your web pages and that can be done using Link and NavLink in React.

In this post we'll see how to use Link to create a link from one page to another and also how to use Link to create a navigational menu.

Link in React Router

In HTML you might have used anchor tag <a href=””> to create a link but using that directly in a React app will result in a full page load which is not what we need in Single page application. We should use Link or NavLink to create such links in a React app.

Link is a wrapper around <a href> to enable navigation with client-side routing. Link uses JavaScript and the browser's history API to update the page content.

Using Link to navigate from one page to another

Link has a "to" props which is used to specify the path that will be added to the URL once the link is clicked. That path is then used by routing definition to match it to the component that is called.

src\components\routes\Home.js

import { Link } from "react-router";
const Home = () => {
    return (
    <>
        <h2>This is home page</h2>
        <Link to="/about">About</Link>
    </>
    )
}
export default Home;

src\components\routes\About.js

const About = () => {
    return <h2>This is about page</h2>
}

export default About;

App.js

That's where routing is configured.

import { BrowserRouter, Route, Routes } from 'react-router';
import About from './components/routes/About';
import Home from './components/routes/Home';

function App() {
  return (
    <>
      <BrowserRouter >
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="about" element={<About />} />
        </Routes>
      </BrowserRouter>
    </>
  );
}

export default App;

With that if you access the root URL- http://localhost:3000/

Link in React Router

Clicking on the "About" link will take you to the About page.

Creating Navigation Menu using Link in React Router

If you want to create a menu as a header that is always there and provides navigation across web application that also can be done using Link in React Router.

You can create a separate file for the menu, note that it uses Bootstrap 5 components for styling.

src\components\routes\Navigation.js

import { Link } from "react-router";

const Navigation = () => {
    return(
        <>
            <nav className="navbar navbar-expand-lg bg-dark navbar-dark">
                <div className="container-fluid">
                    <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarMenu" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                        <span className="navbar-toggler-icon"></span>
                    </button>

                    <div className="collapse navbar-collapse" id="navbarMenu">
                        <ul className="navbar-nav">
                            <li className="nav-item">
                                <Link className="nav-link" to="/">
                                    Home
                                </Link>
                            </li>
                            <li className="nav-item">
                                <Link className="nav-link" to="/about">
                                    About
                                </Link>
                            </li>
                    </div>
                </div>
            </nav>
        </>
    );
}

export default Navigation;

As you can see using "to" props, path is given with in the Link component.

App.js

Note that <Link/> cannot be rendered outside <BrowserRouter/> so you should add the Navigation component wrapped with in the BrowserRouter.

import { BrowserRouter, Route, Routes } from 'react-router';
import About from './components/routes/About';
import Home from './components/routes/Home';
import Navigation from './components/routes/navigation';
function App() {
  return (
    <>
      <BrowserRouter >
       <Navigation />
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="about" element={<About />} />
        </Routes>
      </BrowserRouter>
    </>
  );
}

export default App;

With these changes if you access the root URL

Navigation menu with Link in React

Navigation menu with child routes and Outlet

In the above example we saw how to create a navigation menu with Link, it works fine but the recommended way to do it is to create routes as child routes of the route that specifies Navigation component as the "element" value.

import { BrowserRouter, Route, Routes } from 'react-router';
import About from './components/routes/About';
import Home from './components/routes/Home';
import Navigation from './components/routes/navigation';
function App() {
  return (
    <>
      <BrowserRouter >
        <Routes>
          <Route path="/" element={<Navigation />}>
            <Route path="/" element={<Home />} />
            <Route path="about" element={<About />} />
          </Route>
        </Routes>
      </BrowserRouter>
    </>
  );
}

export default App;

As you can see Navigation component now acts as a parent route and other components are specified as the child routes.

In the Navigation component add the Outlet so that the matching child route of a parent route is rendered at the place specified by Outlet.

src\components\routes\Navigation.js

import { Link, Outlet } from "react-router";
const Navigation = () => {
    return(
        <>
            <nav className="navbar navbar-expand-lg bg-dark navbar-dark">
                <div className="container-fluid">
                    <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarMenu" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                        <span className="navbar-toggler-icon"></span>
                    </button>

                    <div className="collapse navbar-collapse" id="navbarMenu">
                        <ul className="navbar-nav">
                            <li className="nav-item">
                                <Link className="nav-link" to="/">
                                    Home
                                </Link>
                            </li>
                            <li className="nav-item">
                                <Link className="nav-link" to="/about">
                                    About
                                </Link>
                            </li>
                    </div>
                </div>
            </nav>
      <Outlet />  
        </>
    );
}

export default Navigation;
Link in React

That's all for this topic Link in React Router With Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. React Declarative Approach
  2. React Virtual DOM
  3. React create-react-app Project Structure
  4. JavaScript Rest Parameter

You may also like-

  1. ArrayList in Java With Examples
  2. Count Number of Times Each Character Appears in a String Java Program
  3. Java Stream API Interview Questions And Answers
  4. What is Client Side Routing in Angular

Routing in React With Example

In this post we'll see how to configure routing in React. In any web application you'll use navigation or links to move from one page to another, this routing of users across different web pages based on their actions or requests is done using routing in React.

You might have heard many times that React is used to create single-page application (SPA). Routing enables the navigation in SPA so that content is loaded without refreshing the whole page.

In this post we'll learn how to configure routes using React router which is a library for handling routing and navigation in React JS Applications. Version of React router used is version 7.

Installing React Router

You can install latest version of React Router from npm using the following command

npm i react-router

Routing modes in React Router

As per the React Router documentation there are 3 routing modes.

  1. Declarative- Using Declarative mode in React Router enables basic routing features like matching URLs to components, navigating around the app and providing active states with APIs like <Link>, useNavigate, and useLocation.
    If you are using Declarative mode then you'll use BrowserRouter for configuring routes which is a declarative router using the browser history API for client side routing.
  2. Data- Using Data mode in React Router you can move route configuration outside of React rendering, Data Mode adds data loading, actions, pending states and more with APIs like loader, action, and useFetcher.
    If you are using Data mode then you'll use createBrowserRouter function to create a new data router that manages the application path via history.pushState and history.replaceState.
  3. Framework- Framework Mode wraps Data Mode with a Vite plugin to add the full React Router experience with:
    • typesafe href
    • typesafe Route Module API
    • intelligent code splitting
    • SPA, SSR, and static rendering strategies

React routing example using React Router

In this basic example we'll have two components Home and About which are to be rendered using routing.

We’ll see configuration using both <BrowserRouter> and createBrowserRouter.

Using Declarative mode and BrowserRouter

1. If you are using declarative routing mode with BrowserRouter then first thing is to render a <BrowserRouter> around your application. Navigate to index.js file, import BrowserRouter from react-router and wrap BrowserRouter around the App component.

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
);

2. Creating the components

We need to provide Home and About components.

Home.js

const Home = () => {
    return (
      <>
          <h2>This is home page</h2>
      </>
    )

}

export default Home;

About.js

const About = () => {
    return <h2>This is about page</h2>
}

export default About;

3. Route definition

We can configure routes in App.js file.

import { Route, Routes } from 'react-router';
import About from './components/routes/About';
import Home from './components/routes/Home';

function App() {
  return (
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
  );
}

export default App;

As you can see route definitions are wrapped with in the Routes component and each route definition is provided using the Route component.

Routing configuration is done by mapping path to a component. Which means when the user gives root URL that path is served by Home component. If user adds /about to the root URL then that path is served by About component.

If you access the root path by providing the URL as http://localhost:3000/

If path is changed to http://localhost:3000/about

Using Data mode and createBrowserRouter

If we have to configure routes using createBrowserRouter function for the same Home and About components.

1. Route definition

With Data mode in React Router you can move route configuration outside of React rendering, so you can create a separate file to configure routes.

src\components\routes\Route.js

import { createBrowserRouter } from "react-router";
import About from "./about";
import Home from "./home";

export const route = createBrowserRouter([
   {path: "/", element: <Home /> },
   {path: "/about", element: <About />}
])

createBrowserRouter function takes an array of type RouteObject as its first argument. Each element in this array is an object defining a route using path and element properties.

2. Initializing the route definition

You can provide the route definition to your application by providing it as a value to "router" props in RouterProvider component. This should be done at the top of an app's element tree.

App.js

import { RouterProvider } from 'react-router';
import { route } from './components/routes/Route';

function App() {
  return (
       <RouterProvider router={route}></RouterProvider>
  );
}

export default App;

If you were following the previous Declarative mode example and wrapped App component in index.js with BrowserRouter then please remove that wrapping before running the data mode example.

That's all for this topic Routing in React With Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. React Declarative Approach
  2. React Virtual DOM
  3. React create-react-app Project Structure
  4. JavaScript Rest Parameter

You may also like-

  1. ArrayList in Java With Examples
  2. Count Number of Times Each Character Appears in a String Java Program
  3. Java Stream API Interview Questions And Answers
  4. What is Client Side Routing in Angular