React Answers

How to add navigation with React?

Spread the love

To add navigation with React, we install React Router.

To install it, we run

npm install react-router-dom

Then we use it by writing

import React from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";

export default function App() {
  return (
              <Link to="/">Home</Link>
              <Link to="/about">About</Link>
              <Link to="/users">Users</Link>

          <Route path="/about">
            <About />
          <Route path="/users">
            <Users />
          <Route path="/">
            <Home />

function Home() {
  return <h2>Home</h2>;

function About() {
  return <h2>About</h2>;

function Users() {
  return <h2>Users</h2>;

to add the Switch component with the Route components inside.

The Route components have the route components nested inside them.

The path is set to the path that users navigate to to render the component inside.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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