I have tried for a really long time to figure out how I would go about creating a navigation dropdown using react-router-dom
. My problem is that I want to be able to have the current page selected in the dropdown, and my way of doing that is to keep the selected item in the this.state
variable of the parent. Here is my code currently in the render()
function (I am using react-bootstrap
components for the dropdown):
<Dropdown.Menu className="dropdown-menu-right">
<MenuItem name="bandList"
className={(this.state.activeView === "bandList") ? "active" : ""}
onClick={ this.handleClick } >
Hitta Band
</MenuItem>
<MenuItem name="musiciansList"
className={(this.state.activeView === "musiciansList") ? "active" : ""}
onClick={ this.handleClick } >
Hitta Musiker
</MenuItem>
</Dropdown.Menu>
And the handleClick()
function:
handleClick(event){
var name = event.target.name;
this.setState({
activeView: name
})
}
I have read the thread here: Programmatically navigate using react router
But the ways described there is to create a new component and wrap it inside of either withRouter
function or a <Route>
component, which doensn't work in my case. The problem is that I need to be able to change this.state
and navigate to another route when clicking in the menu. I tried creating a new component and wrapping it inside of withRouter()
like this:
const BandListNav = withRouter(({history}) => (
<MenuItem
name="bandList"
onClick={() => history.push('/bandList')}
>
Hitta Band
</MenuItem>
));
And then in the parent component the render()
function would be:
<Dropdown.Menu className="dropdown-menu-right">
<BandListNav
className={(this.state.activeView === "bandList") ? "active" : ""}
onClick={ this.handleClick }
/>
</Dropdown.Menu>
But in this case the this.handleClick
function would not get called (I guess it gets overridden by the onClick()
function in the BandListNav
component.
Basically what I want to do is to change the state of the parent component while at the same time navigating to another route.
Is there any way to do this using react-router-dom
(v4)?
Any help appreciated. Thanks in advance!