tommyd456
tommyd456

Reputation: 10683

Pass router history to component for onClick

Trying to clean my React app up a little with Container and Presentation components. I'm using react-router v4 and I previously used an onClick event for each job to show a specific job page:

<div onClick={() => this.props.history.push('/jobs/' + job.slug)}>
  //The job info
</div>

Now I've created a dumb component in a separate file for the jobs like this:

const Jobs = (props) => (
  <div>
  {
    props.jobs.map(job =>
      <div key={job.slug} onClick(//todo)>
        <p>{job.title} at <Link to="/">{job.company}</Link></p>
      </div>
    )
  }
  </div>
)

but I can no longer access this.props.history

How can I solve this issue? Should I pass another prop in the following:

<Jobs jobs={jobs}/>

Upvotes: 2

Views: 4922

Answers (1)

Tharaka Wijebandara
Tharaka Wijebandara

Reputation: 8065

To access router objects(match, history and location) via props of the component, either the component has to be rendered via Route or it should wrap with withRouter higher-order component.

Check whether your Jobs component is directly rendered via Route with something like this.

<Route path="/jobs" component={Jobs} />

If it's not the case, and Jobs component is rendered with JSX inside the render method of another component, then wrap it with withRouter higher-order component as follows before you export it.

export default withRouter(Jobs);

This will ensure that Jobs component has access to all the router props.

Also, make sure that you use props.history instead of this.props.history since now it's functional component.

Upvotes: 11

Related Questions