Source:  Twitter logo

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!

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.

1 users liked answer #0dislike answer #01
mxdi9i7 profile pic
mxdi9i7

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

0 users liked answer #1dislike answer #10
moslem profile pic
moslem

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).