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.
Using Link
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.
Thanks for reading!
Check out my recently published Mastering Redux course.
In this course, you will build 3 apps along with food ordering app and you'll learn:
- Basic and advanced Redux
- How to manage the complex state of array and objects
- How to use multiple reducers to manage complex redux state
- How to debug Redux application
- How to use Redux in React using react-redux library to make your app reactive.
- How to use redux-thunk library to handle async API calls and much more
and then finally we'll build a complete food ordering app from scratch with stripe integration for accepting payments and deploy it to the production.
Want to stay up to date with regular content regarding JavaScript, React, Node.js? Follow me on LinkedIn.
Comments (0)