Thursday, 16 January 2025

Mastering Navigation in React with React Router: Installation, Setup, and Simple Application Example

React Router is a JavaScript library for enabling navigation and dynamic routing in React applications. It allows you to build a single-page application (SPA) with multiple views and seamless navigation, enhancing user experience without refreshing the entire page. In this blog post, we'll explore how to install React Router, understand its core concepts, and implement a simple application to demonstrate its power.

Key Features of React Router

·      Declarative routing using JSX.

·      Supports nested routes and layouts.

·      Dynamic routing based on URL parameters.

·      Redirects, protected routes, and more.

 

How to install React Router?

To use React Router in your project, you need to install the react-router-dom package by executing below command from the project root folder.

npm install react-router-dom

 

Above command will install the necessary package to handle routing in your React application.

 

How to define set of routes for your Application?

‘createBrowserRouter’ is a function provided by React Router (v6.4+), which allows you to define a set of routes for your application. These routes decide which components should be rendered when the browser's URL matches a particular path.

 

Example

const router = createBrowserRouter([
  {
    path: "/",
    element: <Home />,
  },
  {
    path: "about",
    element: <About />,
  },
  {
    path: "contact",
    element: <Contact />,
  },
]);

 

const router = createBrowserRouter([...]): This creates a router object using the createBrowserRouter function. This router is used to control the navigation and rendering of different components based on the URL.

 

[...] (Route Configuration Array): The array passed to createBrowserRouter defines a list of route objects. Each object in the array represents a single route configuration.

 

Each route object contains two main properties.

 

1. path: This defines the URL path that will trigger this route. When the browser’s URL matches this path, the associated component (element) will be rendered.

 

·      "/": This is the root path, meaning when the user visits the base URL (e.g., http://localhost:3000/), the Home component will be rendered.

·      "about": When the user visits http://localhost:3000/about, the About component will be rendered.

·      "contact": When the user visits http://localhost:3000/contact, the Contact component will be rendered.

 

2. element: This is the React component that will be rendered when the route is matched.

 

·      <Home />: The Home component will be rendered when the user visits the root path (/).

·      <About />: The About component will be rendered when the user visits the /about path.

·      <Contact />: The Contact component will be rendered when the user visits the /contact path.

 

Specify RouterProvider component

RouterProvider takes the router configuration (router) and enables routing functionality in your application. It acts as the top-level provider, allowing your application to respond to route changes and display the appropriate components for each URL path.

export default function App() {
  return (
    <div>
      <RouterProvider router={router} />
    </div>
  );
}

<RouterProvider>: RouterProvider is a component provided by React Router (v6.4+). It is used to supply the routing logic created by createBrowserRouter to your React application.

 

router={router}: This router prop expects the router object that was created using createBrowserRouter. The router object contains all the route configurations and handles how navigation and URL changes map to different components in the app.

 

Follow below step-by-step procedure to build complete working application.

 

Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘router-hello-world’

 

Step 2: Navigate to the project directory and install react router dom by executing below commands.

 

cd router-hello-world

npm install react-router-dom

 

Project structure looks like below.



 

Step 3: Create pages folder in src folder and define Home, About and Contact pages.

 

Home.jsx

export default function Home() {
  return <h2>Home Page</h2>;
}

 

About.jsx

export default function About() {
  return <h2>About Page</h2>;
}

 

Contact.jsx

export default function Contact() {
  return <h2>Contact Page</h2>;
}

 

Step 4: Update App.jsx with below content.

 

App.jsx

 

import React from "react";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import Home from "./pages/Home";
import About from "./pages/About";
import Contact from "./pages/Contact";

// Create the routes using createBrowserRouter
const router = createBrowserRouter([
  {
    path: "/",
    element: <Home />,
  },
  {
    path: "about",
    element: <About />,
  },
  {
    path: "contact",
    element: <Contact />,
  },
]);

export default function App() {
  return (
    <div>
      <RouterProvider router={router} />
    </div>
  );
}

Step 5: Update main.jsx with below content.

 

main.jsx

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

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

Step 6: Execute below steps to build and run the Application.

  cd router-hello-world
  npm install
  npm run dev

Open the url ‘http://localhost:5173/’ in browser, you can see Home page screen.




Open the url ‘http://localhost:5173/about’ to see the About page.

 


Open the url ‘http://localhost:5173/contact’ to see contact page.

 


You can download the application from this link.


Previous                                                    Next                                                    Home

No comments:

Post a Comment