Tuesday, June 3, 2025

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

In a real world application you will use links to move around web pages and there may also be a navigation menu. Refer this post- Link in React Router With Example and this post- Using NavLink in React Router to see how you can do it with React Router.

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. Index Route in React Router
  2. Nested Route in React Router With Example
  3. Dynamic Route in React Router With Example
  4. Setting 404 Error Page With React Router
  5. Controlled and Uncontrolled Components in React

You may also like-

  1. JSX in React
  2. JavaScript Array slice() method With Examples
  3. How to Sort an ArrayList in Descending Order in Java
  4. Find All Permutations of a Given String Java Program
  5. Difference Between Encapsulation And Abstraction in Java
  6. What is Client Side Routing in Angular

No comments:

Post a Comment