Reputation: 145
I have App component, Create Component and Join Component. I want to display links/navigation to access Create and Join component only on App component. Currently when I click on Create link and Join link I can still see those links.
This is my current setup. App.js
function App(props) {
return (
<Router>
<ul>
<li>
<Link to="/create">Create</Link>
</li>
<li>
<Link to="/join">Join</Link>
</li>
</ul>
<div>
<Switch>
<Route path="/create">
<Create />
</Route>
<Route path="/join">
<Join />
</Route>
</Switch>
</div>
</Router>
);
}
Upvotes: 1
Views: 32
Reputation: 203466
You can place them on a specific, like your "home" route. Router
matches and renders routes inclusively so you will need to specify the exact
prop since "/" path prefix matches all paths.
function App(props) {
return (
<Router>
<Route exact path="/"> // <-- only render when path is exactly "/"
<ul>
<li>
<Link to="/create">Create</Link>
</li>
<li>
<Link to="/join">Join</Link>
</li>
</ul>
</Route>
<div>
<Switch>
<Route path="/create">
<Create />
</Route>
<Route path="/join">
<Join />
</Route>
</Switch>
</div>
</Router>
);
}
Alternatively you can place them on a "generic" route at the end of the Switch
, so if the path doesn't match anything else above it then it'll render. The Switch
exclusively matches and renders routes.
function App(props) {
return (
<Router>
<div>
<Switch>
<Route path="/create">
<Create />
</Route>
<Route path="/join">
<Join />
</Route>
<Route> // <-- matches only if nothing matched above
<ul>
<li>
<Link to="/create">Create</Link>
</li>
<li>
<Link to="/join">Join</Link>
</li>
</ul>
</Route>
</Switch>
</div>
</Router>
);
}
Upvotes: 1