Categories
React Answers

How to add links to a React Router route with React-Bootstrap?

Spread the love

Sometimes, we want to add links to a React Router route with React-Bootstrap.

In this article, we’ll look at how to add links to a React Router route with React-Bootstrap.

How to add links to a React Router route with React-Bootstrap?

To add links to a React Router route with React-Bootstrap, we can use the Nav.Link component.

For instance, we write:

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import { Nav, Navbar } from "react-bootstrap";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  NavLink
} from "react-router-dom";

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

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

const Links = () => {
  return (
    <Navbar>
      <Navbar.Brand as={NavLink} to="/">
        Brand link
      </Navbar.Brand>
      <Nav>
        <Nav.Link as={NavLink} to="/" exact>
          Home
        </Nav.Link>
        <Nav.Link as={NavLink} to="/foo">
          Foo
        </Nav.Link>
        <Nav.Link as={NavLink} to="/bar">
          Bar
        </Nav.Link>
      </Nav>
    </Navbar>
  );
};

export default function App() {
  return (
    <Router>
      <div>
        <Links />
        <Switch>
          <Route path="/foo" children={<Foo />} />
          <Route path="/bar" children={<Bar />} />
        </Switch>
      </div>
    </Router>
  );
}

to add links to the /foo and /bar routes with Nav.Link.

We set the as prop to the React Bootstrap’s NavLink component so that the link is rendered by React Bootstrap and it links to the route defined with React Router.

We set the to prop of each Nav.Link to the route we want to load when we click on the link.

Therefore, we should see ‘foo’ and ‘bar’ when we click on Foo and Bar respectively.

Conclusion

To add links to a React Router route with React-Bootstrap, we can use the Nav.Link component.

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 *