How to pass parameters with history.push, Link, or Redirect in React Router v4?

Sometimes, we want to pass parameters with history.push, Link, or Redirect in React Router v4.

In this article, we’ll look at how to pass parameters with history.push, Link, or Redirect in React Router v4.

How to pass parameters with history.push, Link, or Redirect in React Router v4?

To pass parameters with history.push, Link, or Redirect in React Router v4, we can set the state property.

For instance, we write

this.props.history.push({
  pathname: '/template',
  search: '?query=abc',
  state: {
    detail: response.data
  }
})

to call history.push with an object with the state property to pass props to the history object.

With the Link, component, we write

<Link
  to={{
    pathname: "/template",
    search: "?query=abc",
    state: { detail: response.data },
  }}
>
  My Link
</Link>

to set the to prop to an object with the state property containing the data that we want to pass into the route component as props.

Conclusion

To pass parameters with history.push, Link, or Redirect in React Router v4, we can set the state property.