I was wondering what is the best practice in ReactJS to update a component's content depending on the url. Let say I have a navbar with some buttons in it. I want to display some of the buttons depending on the url.
For exemple, when the url is /home I want my navbar to be:
<nav>
<button>Button 1</button>
<button>Button 2</button>
<button>Button 3</button>
</nav>
And when it's /about I want
<nav>
<button>Button 2</button>
</nav>
My main component would be something like:
<Router>
<Header />
<Switch>
<Route path="/home">
<Home />
</Route>
<Route path="/about">
<About />
</Route>
</Switch>
</Router>
So my navbar is in the <Header/> component.
My first guess would be to use react-router to get the current url and then change what is rendered in the <Header/>
render() {
let buttons
if(location === "/home") {
buttons = <button>Button 1</button><button>Button 2</button><button>Button 3</button>
} else {
buttons = <button>Button 2</button>
}
return (
<nav>
{buttons}
</nav>
)
}
Is it a good practice? Is there a better way? Should I use react-redux for the conditionnal rendering? (I'm new to react-redux and I'm trying to see all the possibilities)
P.S.: the code is not perfect because I typed it quickly direct in the message box sorry for that.
Routein conditional rendering.