I am new to react development. And I want to implement the routing mechanism in my page.
For example, there's component contains routes with the <Home />
and <Login />
component.
function App() {
return (
<div className="App">
<Switch>
<Route exact path="/home">
<Home />
</Route>
<Route path="/login">
<Login />
</Route>
</Switch>
</div>
);
}
The <Home />
component contains a <Navbar />
and a <Switch />
with two <Route />
:
Home.js
function Home() {
return (
<div>
<Navbar />
<div>
<Switch>
<Route exact path={`/home`}>
<Menu />
</Route>
<Route path={`/home/temperature`}>
<div>temperature</div>
</Route>
</Switch>
</div>
</div>
)
}
However, I defined the <Link />
in the <Menu />
component as below:
function Menu() {
return (
<div>
<li>
<Link to={`/home/temperature`}>temperature child page</Link>
</li>
</div>
)
}
Originally, the page would displayed the <Home />
component with <Menu />
and <div> temperature </div>
I expected that when I clicked the link (<Link to={
/home/temperature}>temperature child page</Link>
) then it would replace the <Menu />
component with the only the <div>temperature</div>
(Dispalyed the <Navbar/>
and <div>temperature</div>
, but it could not display anything.
How should I correct it?
Solution:
I finally figure out why I cannot get child component in my js script.
Firstly, I need to wrap the <Switch>
with <Router>
in <App>
component.
Then, by reference this , I realized that I should not specify the exact
in <Route path="/home">
to make sure that the nested route can work as well.
function App() {
return (
<div className="App">
<Router>
<div>
<Switch>
<Route path="/home">
<Home />
</Route>
<Route path="/login">
<Login />
</Route>
</Switch>
</div>
</Router>
</div>
);
}