0

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>
  );
}
william
  • 13
  • 3
  • why don't you just define your routes globally? There is no need to put another switch inside your component. Just put it all into your – Tim Gerhard Dec 04 '19 at 07:26
  • @TimGerhard, I followed the example from https://reacttraining.com/react-router/web/example/nesting, I thought putting the switch inside the component is a correct way. – william Dec 04 '19 at 07:43

1 Answers1

0

simple routing

<Router>
    <Switch>
        <Route path={"/home"} exact component={Home} />
    </Switch>
</Router>

nested routing

<Router>
     <Switch>
         <Route path={"/home"} exact component={Home}
             <Rout path={"/temperature"} exact component={Temperature} />
         </Route>
    </Switch>
</Router>

`