My React project’s App.js file has routes like so:
JavaScript
x
11
11
1
<div>
2
<Background />
3
<Navbarr />
4
<Switch>
5
<Route path="/" component={Home} exact />
6
<Route path="/news" component={News} />
7
<Route path="/reserve" component={Reserve} />
8
<Route path="/admin" component={Admin} />
9
</Switch>
10
</div>
11
In my Navbarr component, I have Links that set the routes, e.g.:
JavaScript
1
9
1
<Nav.Link
2
href="/news"
3
name="news"
4
active={active === "/news"}
5
onClick={() => setActive("/news")}
6
>
7
News
8
</Nav.Link>
9
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
JavaScript
1
11
11
1
import { Link } from "react-router-dom";
2
3
<Link
4
to="/news"
5
name="news"
6
active={active === "/news"}
7
onClick={() => setActive("/news")}
8
>
9
News
10
</Link>
11
Alternatively, you can leverage the as
prop of React-bootstrap
JavaScript
1
12
12
1
import { Link } from "react-router-dom";
2
3
<Nav.Link
4
as={Link} // --> render as react-router-dom Link
5
to="/news"
6
name="news"
7
active={active === "/news"}
8
onClick={() => setActive("/news")}
9
>
10
News
11
</Nav.Link>
12