This content originally appeared on DEV Community and was authored by Med Amine Fh
If you've used React Router on many projects, definitely you've asked How i can pass some data or state to other components through a link tag?.
So 1st of all we'll discuss how we can pass data between components in React.
1. Passing props
The 1st one is by passing some props from the parent component to the children components
2. Global State
2nd one is by making a Global State and make some data accessible by many components.
You can manage Global State using two main paths:
3. Using React Router's Link
3rd one is basically when you click on a link(to component), you passing data with that.
Below we Have a simple React App with some routes
We Have two routes Here the "/
"(Home) Route and the "/profile
"(Profile) route.
So the 1st page we'll see if we run yarn start
is the Home Page
And if we go to the /profile route
we'll see the Profile component
So as you can see we're using the <Link>
instead of the regular <a>
tag to prevent the refresh of the page.
So how we can send data for exemple to the Profile component from the Home component ?
So the cool thing is we can pass an Object to the to property in the <Link>
and that object must contains a pathname
and optionally a state
, and we can pass the data through that state
and we can access that state in the Profile component in the props.location.state
for more Info check this React Router Link
This content originally appeared on DEV Community and was authored by Med Amine Fh
Med Amine Fh | Sciencx (2021-10-01T12:50:52+00:00) Passing Data with React Router using Link. Retrieved from https://www.scien.cx/2021/10/01/passing-data-with-react-router-using-link/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.