React Router

Introduction

In this chapter, we will explore React Router, a powerful library for handling routing in React applications. React Router allows you to create single-page applications with navigation and dynamic content. We will use the latest version of React Router to demonstrate how to set up routing in a simple website.

Table of Contents

  1. Setting Up a New React Project
  2. Installing React Router
  3. Basic Configuration
  4. Creating Routes
    • Example: Home, About, and Contact Pages
  5. Using Links for Navigation
    • Example: Navigation Menu
  6. Nested Routes
    • Example: Nested Route for Services
  7. Redirects and Not Found Pages
    • Example: 404 Page and Redirects
  8. Conclusion

Setting Up a New React Project

First, let’s create a new React project using the create-react-app tool.

  1. Open your terminal and run the following command:
    npx create-react-app react-router-example
    
  2. Navigate to the project directory:
    cd react-router-example
    

Installing React Router

Next, let’s install React Router. Open your terminal and run the following command inside your project directory:

npm install react-router-dom

Basic Configuration

package.json

After installing React Router, your package.json should look something like this (relevant sections shown):

{
  "name": "react-router-example",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^18.0.0",
    "react-dom": "^18.0.0",
    "react-router-dom": "^6.0.0",
    "react-scripts": "5.0.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  // other configurations...
}

Basic Configuration

  1. Create a New File for Routes: In the src directory, create a new file named AppRouter.js.
  2. Define the Routes: Add the following code to AppRouter.js to set up basic routing:
    // src/AppRouter.js
    import React from 'react';
    import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
    import Home from './Home';
    import About from './About';
    import Contact from './Contact';
    import NotFound from './NotFound';
    
    function AppRouter() {
      return (
        <Router>
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/about" element={<About />} />
            <Route path="/contact" element={<Contact />} />
            <Route path="*" element={<NotFound />} />
          </Routes>
        </Router>
      );
    }
    
    export default AppRouter;
    

    Explanation:

    • BrowserRouter is used to wrap the application and enable routing.
    • Routes is used to define the route configuration.
    • Route is used to define paths and their corresponding components.
    • NotFound component is rendered for any undefined routes.
  3. Create the Page Components: Create Home.js, About.js, Contact.js, and NotFound.js in the src directory with the following content:
    // src/Home.js
    import React from 'react';
    
    function Home() {
      return <h2>Home Page</h2>;
    }
    
    export default Home;
    
    // src/About.js
    import React from 'react';
    
    function About() {
      return <h2>About Page</h2>;
    }
    
    export default About;
    
    // src/Contact.js
    import React from 'react';
    
    function Contact() {
      return <h2>Contact Page</h2>;
    }
    
    export default Contact;
    
    // src/NotFound.js
    import React from 'react';
    
    function NotFound() {
      return <h2>404 - Page Not Found</h2>;
    }
    
    export default NotFound;
    
  4. Use the Router in App.js: Open src/App.js and modify the App component to use the AppRouter component:
    // src/App.js
    import React from 'react';
    import AppRouter from './AppRouter';
    
    function App() {
      return (
        <div>
          <AppRouter />
        </div>
      );
    }
    
    export default App;
    
  5. Save and View Changes: Save the files and start your React application by running:
    npm start
    

    Open your browser and navigate to http://localhost:3000. You should see the home page. You can navigate to /about and /contact to see the respective pages.

To enable navigation between pages, we use the Link component from react-router-dom.

Example: Navigation Menu

  1. Create a Navigation Component: In the src directory, create a new file named Nav.js.
  2. Define the Navigation Component: Add the following code to Nav.js:
    // src/Nav.js
    import React from 'react';
    import { Link } from 'react-router-dom';
    
    function Nav() {
      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 Nav;
    
  3. Include the Navigation in AppRouter: Open src/AppRouter.js and include the Nav component:
    // src/AppRouter.js
    import React from 'react';
    import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
    import Home from './Home';
    import About from './About';
    import Contact from './Contact';
    import NotFound from './NotFound';
    import Nav from './Nav';
    
    function AppRouter() {
      return (
        <Router>
          <Nav />
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/about" element={<About />} />
            <Route path="/contact" element={<Contact />} />
            <Route path="*" element={<NotFound />} />
          </Routes>
        </Router>
      );
    }
    
    export default AppRouter;
    
  4. Save and View Changes: Save the files and start your React application by running:
    npm start
    

    You should now see a navigation menu that allows you to navigate between the Home, About, and Contact pages.

Nested Routes

Example: Nested Route for Services

  1. Create a Services Component: In the src directory, create a new file named Services.js.
  2. Define the Services Component: Add the following code to Services.js:
    // src/Services.js
    import React from 'react';
    import { Route, Routes, Link } from 'react-router-dom';
    
    function Services() {
      return (
        <div>
          <h2>Services</h2>
          <ul>
            <li>
              <Link to="web-development">Web Development</Link>
            </li>
            <li>
              <Link to="app-development">App Development</Link>
            </li>
          </ul>
          <Routes>
            <Route path="web-development" element={<WebDevelopment />} />
            <Route path="app-development" element={<AppDevelopment />} />
          </Routes>
        </div>
      );
    }
    
    function WebDevelopment() {
      return <h3>Web Development Service</h3>;
    }
    
    function AppDevelopment() {
      return <h3>App Development Service</h3>;
    }
    
    export default Services;
    
  3. Add the Services Route: Open src/AppRouter.js and add the Services route:
    // src/AppRouter.js
    import React from 'react';
    import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
    import Home from './Home';
    import About from './About';
    import Contact from './Contact';
    import NotFound from './NotFound';
    import Services from './Services';
    import Nav from './Nav';
    
    function AppRouter() {
      return (
        <Router>
          <Nav />
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/about" element={<About />} />
            <Route path="/contact" element={<Contact />} />
            <Route path="/services/*" element={<Services />} />
            <Route path="*" element={<NotFound />} />
          </Routes>
        </Router>
      );
    }
    
    export default AppRouter;
    
  4. Update the Navigation Component: Open src/Nav.js and add a link to the Services page:
    // src/Nav.js
    import React from 'react';
    import { Link } from 'react-router-dom';
    
    function Nav() {
      return (
        <nav>
          <ul>
            <li>
             <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about">About</Link>
            </li>
            <li>
              <Link to="/contact">Contact</Link>
            </li>
            <li>
              <Link to="/services">Services</Link>
            </li>
          </ul>
        </nav>
      );
    }
    
    export default Nav;
    
  5. Save and View Changes: Save the files and start your React application by running:
    npm start
    

    You should now see a nested route structure under the Services page, allowing you to navigate between Web Development and App Development services.

Redirects and Not Found Pages

Example: 404 Page and Redirects

  1. Update NotFound.js: Ensure your NotFound.js displays a user-friendly message.
    // src/NotFound.js
    import React from 'react';
    import { Link } from 'react-router-dom';
    
    function NotFound() {
      return (
        <div>
          <h2>404 - Page Not Found</h2>
          <p>
            Go back to <Link to="/">Home</Link>
          </p>
        </div>
      );
    }
    
    export default NotFound;
    
  2. Update AppRouter.js: Ensure you have a wildcard route (*) to handle undefined routes.
    // src/AppRouter.js
    import React from 'react';
    import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
    import Home from './Home';
    import About from './About';
    import Contact from './Contact';
    import NotFound from './NotFound';
    import Services from './Services';
    import Nav from './Nav';
    
    function AppRouter() {
      return (
        <Router>
          <Nav />
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/about" element={<About />} />
            <Route path="/contact" element={<Contact />} />
            <Route path="/services/*" element={<Services />} />
            <Route path="*" element={<NotFound />} />
          </Routes>
        </Router>
      );
    }
    
    export default AppRouter;
    
  3. Save and View Changes: Save the files and start your React application by running:
    npm start
    

    Now, navigating to any undefined route should display the 404 – Page Not Found message with a link to go back to the Home page.

Conclusion

In this chapter, we set up a new React project and configured React Router to handle navigation. We covered creating basic routes, using links for navigation, handling nested routes, and implementing redirects and not found pages. React Router provides a powerful and flexible way to manage navigation and routing in your React applications, enabling you to build dynamic and user-friendly single-page applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top