Implementing React Navigation Features

ReactReactIntermediate
Practice Now

Introduction

In this project, you will learn how to implement navigation features in a React application. You will create a simple application with a navigation bar and pages that can be navigated to using links.

👀 Preview

project preview

ðŸŽŊ Tasks

In this project, you will learn:

  • How to set up the project and install dependencies
  • How to add routes and route matchers to enable navigation of the menus in the navigation bar
  • How to add navigation from the card list to individual cards

🏆 Achievements

After completing this project, you will be able to:

  • Use React Router to handle client-side routing
  • Create links and navigate between different pages in a React application
  • Pass data between components using the state object in React Router

Set Up the Project

In this step, you will learn how to set up the project and install the necessary dependencies.

Open your code editor and navigate to the project directory.

├── public
├── src
│   ├── App.css
│   ├── App.js
│   ├── components
│   │   ├── Card.js
│   │   ├── Cards.js
│   │   └── Home.js
│   ├── index.css
│   ├── index.js
│   ├── reportWebVitals.js
│   └── setupTests.js
├── package-lock.json
└── package.json

Next, download the dependencies using the npm install command in the terminal, wait for the dependencies to finish downloading and then start the project using the npm start command.

Once the project starts successfully, click on the "Web 8080" to preview it in your browser.

Add Routes and Route Matchers

In this step, you will learn how to add routes and route matchers to enable navigation of the menus in the navigation bar.

  1. Open the src/index.js file and import the necessary modules:

    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-dom";
  2. Wrap the App component with the BrowserRouter component:

    root.render(
      <BrowserRouter>
        <App />
      </BrowserRouter>
    );
  3. Open the src/App.js file and import the necessary components and modules:

    import React from "react";
    import { Route, Switch, Link } from "react-router-dom";
    import { Home } from "./components/Home";
    import { Cards } from "./components/Cards";
    import { Card } from "./components/Card";
    import "./App.css";
  4. Add the navigation menu and the Switch component to handle the different routes:

    const App = () => {
      return (
        <div className="app">
          <header>
            <Link to="/" className="menu menu-1">
              homepage
            </Link>
            <Link to="/cards" className="menu menu-2">
              card page
            </Link>
          </header>
          <Switch>
            <Route path="/" exact component={Home} />
            <Route path="/cards" exact component={Cards} />
            <Route path="/cards/:id" component={Card} />
          </Switch>
        </div>
      );
    };

    The Switch component ensures that only one route is rendered at a time, and the Route components define the different routes and the corresponding components to be rendered.

In this step, you will learn how to add code to jump from the card list page to the individual card pages.

  1. Open the src/components/Cards.js file and import the necessary modules:

    import React from "react";
    import { Link } from "react-router-dom";
  2. Add the code to render the card list with links to the individual card pages:

    export const Cards = () => {
      const colors = ["#26547c", "#ef476f", "#ffd166", "#06d6a0"];
    
      return (
        <div className="page cards">
          {colors.map((c, idx) => {
            return (
              <Link
                key={idx}
                to={{
                  pathname: `/cards/${idx + 1}`,
                  state: { bgColor: c }
                }}
              >
                <div
                  className={`card card-${idx + 1}`}
                  style={{ backgroundColor: c }}
                >
                  Card {idx + 1}
                </div>
              </Link>
            );
          })}
        </div>
      );
    };

    The Link component is used to create links to the individual card pages, and the to prop is used to specify the path and the state to be passed to the Card component.

  3. Open the src/components/Card.js file and import the necessary modules:

    import React from "react";
    import { useParams, useLocation } from "react-router-dom";
  4. Add the code to render the individual card page:

    export const Card = () => {
      const { id } = useParams();
      const { state } = useLocation();
    
      return (
        <div
          className="page card-page"
          style={{ backgroundColor: state.bgColor }}
        >
          <p>Card {id}</p>
        </div>
      );
    };

    The useParams hook is used to retrieve the id parameter from the URL, and the useLocation hook is used to retrieve the state object that was passed from the Cards component.

Now, you have completed the project. The finished result is shown in the following screenshot. Clicking on the card page will take you to the card list page, and clicking on each card will take you to the individual card page.

finished
âœĻ Check Solution and Practice

Summary

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like