Skip to main content

Command Palette

Search for a command to run...

How to pass additional data while redirecting to a different route in React

Published
2 min read
How to pass additional data while redirecting to a different route in React
Y

Full Stack Developer | Freelancer | JavaScript | React | Nodejs.

Loves sharing knowledge through technical articles.

Dev.to: https://dev.to/myogeshchavan97

https://linktr.ee/myogeshchavan97

In this article, we will see how we can pass extra data while redirecting to a different route in React that uses react-router-dom library.

So let’s get started.

Normally we use the Link component from react-router-dom as shown below:

<Link to="/register">Register</Link>

So when we click on the Register link, it will redirect to the /register route. But Link also allows us to pass additional data while redirecting.

<Link to={{ 
 pathname: "/register", 
 state: data_you_need_to_pass 
}}>
 Register
</Link>

Here, at the place of data_you_need_to_pass, we can pass a string or object, array and so on and in the /register route we will get that data in props.location.state.

Instead of naming the variable as state, we can use any name but it’s generally called state.


Using history.push

Normally, to redirect using the push method, we use it like this:

props.history.push('/register');

If you need to do some processing before sending the data like removing some values or to trim the values or make some API call, we can call a handler on the submit button click and pass data as shown below:

props.history.push({ 
 pathname: '/register',
 state: data_you_need_to_pass
});

That’s it for today. I hope you learned something new.

I hope you've been enjoying my articles and tutorials I've been writing. If you found them useful, consider buying me a coffee! I would really appreciate it.

Don’t forget to subscribe to get my weekly newsletter with amazing tips, tricks, and articles directly in your inbox here.

More from this blog

Yogesh Chavan

125 posts

Full Stack Developer | JavaScript | React | Nodejs. Subscribe to my YouTube Channel: https://www.youtube.com/@codingmastery_dev