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

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/DOMManipulationGroup(["`DOM Manipulation`"]) javascript(("`JavaScript`")) -.-> javascript/ToolsandEnvironmentGroup(["`Tools and Environment`"]) javascript(("`JavaScript`")) -.-> javascript/SecurityGroup(["`Security`"]) react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/RoutingGroup(["`Routing`"]) react(("`React`")) -.-> react/StylingGroup(["`Styling`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/loops("`Loops`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") javascript/AdvancedConceptsGroup -.-> javascript/template_lit("`Template Literals`") javascript/AdvancedConceptsGroup -.-> javascript/es6("`ES6 Features`") javascript/DOMManipulationGroup -.-> javascript/dom_select("`DOM Selection`") javascript/ToolsandEnvironmentGroup -.-> javascript/debugging("`Debugging`") javascript/ToolsandEnvironmentGroup -.-> javascript/bom("`Browser Object Model`") javascript/SecurityGroup -.-> javascript/web_sec("`Web Security Basics`") react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/list_keys("`Lists and Keys`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/RoutingGroup -.-> react/router_basic("`React Router Basics`") react/StylingGroup -.-> react/css_in_react("`CSS in React`") subgraph Lab Skills javascript/variables -.-> lab-300142{{"`Implementing React Navigation Features`"}} javascript/data_types -.-> lab-300142{{"`Implementing React Navigation Features`"}} javascript/arith_ops -.-> lab-300142{{"`Implementing React Navigation Features`"}} javascript/comp_ops -.-> lab-300142{{"`Implementing React Navigation Features`"}} javascript/loops -.-> lab-300142{{"`Implementing React Navigation Features`"}} javascript/higher_funcs -.-> lab-300142{{"`Implementing React Navigation Features`"}} javascript/destr_assign -.-> lab-300142{{"`Implementing React Navigation Features`"}} javascript/template_lit -.-> lab-300142{{"`Implementing React Navigation Features`"}} javascript/es6 -.-> lab-300142{{"`Implementing React Navigation Features`"}} javascript/dom_select -.-> lab-300142{{"`Implementing React Navigation Features`"}} javascript/debugging -.-> lab-300142{{"`Implementing React Navigation Features`"}} javascript/bom -.-> lab-300142{{"`Implementing React Navigation Features`"}} javascript/web_sec -.-> lab-300142{{"`Implementing React Navigation Features`"}} react/jsx -.-> lab-300142{{"`Implementing React Navigation Features`"}} react/list_keys -.-> lab-300142{{"`Implementing React Navigation Features`"}} react/hooks -.-> lab-300142{{"`Implementing React Navigation Features`"}} react/router_basic -.-> lab-300142{{"`Implementing React Navigation Features`"}} react/css_in_react -.-> lab-300142{{"`Implementing React Navigation Features`"}} end

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

Summary

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

Other React Tutorials you may like