I have tried using <Switch>
and exact
after viewing this post: React Router v4 renders multiple routes but it hasn’t resolved my problem, which is that 2 of my components are rendered at the same time when the <Link>
function operates.
The code:
JavaScript
x
31
31
1
import React from "react";
2
import '../styles/Onboarding.css';
3
import {Link, Route, BrowserRouter as Router, Switch } from "react-router-dom";
4
5
function ComponentA() {
6
7
return (
8
<Router>
9
<div className="parent">
10
<h1 className="title">title</h1>
11
<p className="description">description</p>
12
<Link exact to="/componentB"><button className="button">enter</button></Link>
13
<Switch>
14
<Route exact path="/componentB" component={ComponentB} />
15
</Switch>
16
</div>
17
</Router>
18
);
19
}
20
21
22
function ComponentB() {
23
return (
24
<div>
25
Welcome to ComponentB
26
</div>
27
)
28
}
29
30
export default ComponentA;
31
The result is the html of Component A showing up and “Welcome to ComponentB” underneath them. Please help me out with this reaact-router
issue
Advertisement
Answer
Contents of ComponentA
shows up because ComponentB
is now a child route of ComponentA
. To render them separately, need a parent component like this:
JavaScript
1
11
11
1
export default function App() {
2
return (
3
<Router>
4
<Switch>
5
<Route exact path="/componentA" component={ComponentA} />
6
<Route exact path="/componentB" component={ComponentB} />
7
</Switch>
8
</Router>
9
);
10
}
11