Skip to content
Advertisement

Is there a way to not reload the whole html body with React Routers?

My React project’s App.js file has routes like so:

<div>
        <Background />
        <Navbarr />
        <Switch>
          <Route path="/" component={Home} exact />
          <Route path="/news" component={News} />
          <Route path="/reserve" component={Reserve} />
          <Route path="/admin" component={Admin} />
        </Switch>
</div>

In my Navbarr component, I have Links that set the routes, e.g.:

<Nav.Link
    href="/news"
    name="news"
    active={active === "/news"}
    onClick={() => setActive("/news")} 
>
News
</Nav.Link>

When I click on any of the links, I would like it to just change the component in my <Switch>. Instead, it seems to re-load the whole html body (my background component flashes, even though it has the same picture).

Is there a way to do this?

Advertisement

Answer

You can use react-router-dom‘s Link and use to prop instead of href to use client-side-routing

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

<Link
    to="/news"
    name="news"
    active={active === "/news"}
    onClick={() => setActive("/news")} 
>
News
</Link>

Alternatively, you can leverage the as prop of React-bootstrap

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

<Nav.Link
  as={Link} // --> render as react-router-dom Link
  to="/news"
  name="news"
  active={active === "/news"}
  onClick={() => setActive("/news")}
>
  News
</Nav.Link>
Advertisement