How to switch between pages in React?

Sometimes, we want to switch between pages in React.

In this article, we’ll look at how to switch between pages in React.

How to switch between pages in React?

To switch between pages in React, we can use the React Router package.

To install it, we run:

npm i react-router

Then to use it, we write:

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

const Foo = () => {
  return <p>foo</p>;
};

const Bar = () => {
  return <p>bar</p>;
};

export default function App() {
  return (
    <Router>
      <style>{`.is-active { font-weight: bold }`}</style>
      <div>
        <ul>
          <li>
            <NavLink to="/foo" activeClassName="is-active">
              foo
            </NavLink>
          </li>
          <li>
            <NavLink to="/bar" activeClassName="is-active">
              bar
            </NavLink>
          </li>
        </ul>

        <Switch>
          <Route path="/foo" children={<Foo />} />
          <Route path="/bar" children={<Bar />} />
        </Switch>
      </div>
    </Router>
  );
}

First, we create the Foo and Bar page components.

Next, we add the Routes to map the URLs to the components to render.

Then we add the NavLinks to add links that lets us set the class name of the active link.

We set activeClassName to a string for the class name of the active link.

In the style element, we add a string to style anything with the is-active class by making the font bold.

Therefore, when we click on the links, we’ll see the link for the current page bolded.

Conclusion

To switch between pages in React, we can use the React Router package.