How to avoid reloading the entire app when using Nav.Link from React-Bootstrap?

Viewed 1697

When I use the following link, my React app works as intended, meaning if I click a link, the app does not entirely reload but just changes its front end appearance.

<Link to="/about">About</Link>

Now I want to use a Navbar from React-Bootstrap. However, if I click the Navbar, my entire web app reloads which I don't want.

This is I think the relevant part of my code:

  <Router>

<Navbar bg="dark" variant="dark">
  <Navbar.Toggle aria-controls="basic-navbar-nav" />
  <Navbar.Collapse id="basic-navbar-nav">
    <Nav className="mr-auto">
      <Nav.Link to="/about">Page 1</Nav.Link>
      <Nav.Link href="/about2">Page 2</Nav.Link>
    </Nav>
  </Navbar.Collapse>
</Navbar>

<hr />

        <Switch>
          <Route exact path="/">
            <Home />
          </Route>
          <Route path="/about">
            <About />
          </Route>
          <Route path="/about2">
            <About />
          </Route>
          <Route path="/dashboard">
            <Dashboard />
          </Route>
        </Switch>
         
    </Router>

When I use "to", it doesn't even work at all. When I use "href", the reference works, but the entire web app reloads - this is not really what I want. How can I fix this? Thanks in advance!

1 Answers

In order for React-router to pick up a routing change, you have to use the Link component that comes with the library or handle the redirection programmatically. Fortunately, React-bootstrap provides a render prop in most of its components to specify which component or element you want to render if you don't want the default.

So if you try this instead

import { Link } from 'react-router-dom';

<Nav.Link as={Link} to="/about">Page 1</Nav.Link>

Your navigation should work fine.

Related