Reputation: 117
I have my application and I'm using react-router.On every route I have rendered Navbar and in the Navbar I have input field which I want to render only on two routes. How can I do it ? Is there any "If" that can I use to render part of component when route is matched ?
Upvotes: 0
Views: 96
Reputation: 9787
In your Route
you will have a collection of RouteParams
(match, location and history). You can use e.g. the location.pathname to conditionally render whatever you want.
Something like:
<Router>
<Route render={({match,location,history})=>{
const showNavFields = location.pathname==='/your-path'
return {
<NavBar showNavFields={showNavFields}/>
}
}}/>
<Switch>
<Route path="/your-path" component="AComponent"/ >
<Route path="/your-other-path" component="AnotherComponent"/ >
</Switch>
</Router>
Upvotes: 1
Reputation: 11257
We can use match.url for that.
Working code. Here we are appending route matched
to router url if route is /topics/rendering
import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
function BasicExample() {
return (
<Router>
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/topics">Topics</Link>
</li>
</ul>
<hr />
<Route exact path="/" component={Home} />
<Route path="/topics" component={Topics} />
</div>
</Router>
);
}
function Home() {
return (
<div>
<h2>Home</h2>
</div>
);
}
function Topics({ match }) {
return (
<div>
<h2>Topics</h2>
<ul>
<li>
<Link to={`${match.url}/rendering`}>Rendering with React</Link>
</li>
<li>
<Link to={`${match.url}/components`}>Components</Link>
</li>
</ul>
<Route path={`${match.path}/:topicId`} component={Topic} />
<Route
exact
path={match.path}
render={() => <h3>Please select a topic.</h3>}
/>
</div>
);
}
function Topic({ match }) {
if (match.url === '/topics/rendering') {
return (
<div>
<h3>route matched {match.params.topicId}</h3>
</div>
)
} else {
return (
<div>
<h3>{match.params.topicId}</h3>
</div>
)
}
}
export default BasicExample;
Upvotes: 1