How to pass object through Link in React Router?

Sometimes, we want to pass object through Link in React Router,.

In this article, we’ll look at how to pass object through Link in React Router.

How to pass object through Link in React Router?

To pass object through Link in React Router, we can pass them as a query string.

For instance, we write

<Link
  to={{
    pathname: `/blog/${post.id}`,
    query: {
      title: post.title,
      content: post.content,
      comments: JSON.stringify(post.comments),
    },
  }}
>
  Read More...
</Link>;

to add a Link.

Then we set query to an object with the values we want in the query string.

The keys are the query parameters keys and the values are their values.

Then we can parse the comments from the query parameter with

JSON.parse(this.props.comments)

in the destination component.

Conclusion

To pass object through Link in React Router, we can pass them as a query string.