Search code examples
javascriptreactjsreact-router-v4reactstrap

React router4: update state at onClick Link component


I have a Route component that will render a row of table based on the current url, the problem is i can't update state with onClick that i put on Link component, the url is changed but the state is still the same, so the rendered row content is still the same, look at this code bewlow:

      <Route
        exact
        path={'/dashboard/:page'}
        render={() => (
          this.state.data &&
            data.map((data, index) =>
            <Row key={index}>
               <Col md="1" xl="1">{index + 1}</Col>
               <Col md="3" xl="4">{data.job_title}</Col>
               <Col md="2" xl="3">{data.city}</Col>
               <Col md="2" xl="2">{data.job_status}</Col>
               <Col md="2" xl="2"><a href="">{data.inbox.length > 1 ? data.inbox + ' Candidates' : data.inbox + ' Candidate'}</a></Col>
            </Row>
          )
        )}
      />
      <Route
        exact
        path={'/dashboard'}
        render={() => (
          this.state.data &&
            data.map((data, index) =>
            <Row key={index}>
               <Col md="1" xl="1">{index + 1}</Col>
               <Col md="3" xl="4">{data.job_title}</Col>
               <Col md="2" xl="3">{data.city}</Col>
               <Col md="2" xl="2">{data.job_status}</Col>
               <Col md="2" xl="2"><a href="">{data.inbox.length > 1 ? data.inbox + ' Candidates' : data.inbox + ' Candidate'}</a></Col>
            </Row>
          )
        )}
      />
    </div>
    <div style={{display: 'flex', justifyContent: 'center'}}>
      <Link onClick={() => {this.setState({currentPage: this.state.currentPage + 1, data: dataMock.data[this.state.currentPage + 1]})}} to="/dashboard/1">
        <Button style={{margin: '20px'}}>Page + 1</Button>
      </Link>
      <Link onClick={() => {this.setState({currentPage: this.state.currentPage - 1, data: dataMock.data[this.state.currentPage - 1]})}} to='/dashboard/2'>
        <Button style={{margin: '20px'}}>Page - 1</Button>
      </Link>
    </div>

the question is how can i update the state with the new one? it seems the state is not updated, am i doing it wrong? and i'm a bit confused with this solution i found earlier, here's the link: React to url change within component with React Router 4?


Solution

  • I am not usre if that's a good practise. But an easier fix would be Add the click event to the button, then onClick, do the setState, on setState's call back this.props.history.push('Route')

    for example,

    takeUserToPage = () => {
      this.setState({currentPage: this.state.currentPage + 1, data: 
       dataMock.data[this.state.currentPage + 1]}, () => {
       this.props.history.push('Route')
      });
    }
    
    //inside your return
     <Button style={{margin: '20px'}} onClick={this.takeUserToPage}>Page + 1</Button>