How to change state based on Route change in React-Router?

Viewed 9516

I'm trying to figure out how to change the state of my Dashboard when a new route is clicked. This new route change needs to update the TopMenu component.


This is the code for the Dashboard

class Dashboard extends Component {
  constructor (props) {
    super(props)
    this.state = {
        selectedMenuItem: 'Now'
    }
  }

render () {
return (
  <Router>
    <div id='dashboard-container'>
      <LeftMenu/>

      <div className='column'>
        <TopMenu selectedMenuItem={this.state.selectedMenuItem} />

        <div id='content-container'>
          <div>
            <Switch>
              <Route exact path='/' component={Now} />
              <Route exact path='/surveys' component={Surveys} />
              <Route exact path='/my-questions' />
              <Route exact path='/feedback' />
              <Route exact path='/logout' />
              <Route render={function () {
                            return <p>Not Found</p>
                        }} />
            </Switch>
          </div>
        </div>
      </div>
        </div>

  </Router>

)}}

This is the code for the TopMenu

class TopMenu extends Component {
  render () {
    return (
       <h3>{this.props.selectedMenuItem}</h3>
    )
  }
}

How do I listen to a change in React Router such that I can change the 'selectedMenuItem' state variable in the Dashboard and pass that to TopMenu.

Thanks!

2 Answers

Assuming you are using version 4, check the usage of match in React Router 4: https://reacttraining.com/react-router/web/api/match

match will include all the path information you will need to handle route changes. You can access it by calling this.props.match in your top level page component.

I had the same problem and I solved it with withRouter which is build for integrate router with redux, the only thing you need to do is wrap your connect with withRouter. for more information read redux integration document

Related