I need some help how to open the same url with react-router
Link
but sending different state.
<Link
to={items.vehicleModelId === 2
? '/ecgo-3'
: items.vehicleModelId === 3 && '/ecgo-5'
}
state={{ id: items.id }}
>
{items.name}
</Link>
For example I have 2 links to "/ecgo-5"
but I need to send different state for each one of them. When I am already on "/ecgo-5"
path and then I click the the another link to send the different state, the page wont refresh with the new state.
Any idea how to do it?
2
Answers
You can modify the to prop of the Link component dynamically based on the condition you mentioned. However, the state object should be provided as a prop directly to the Link component, not as part of the to prop. Here’s an example:
In this example, the to prop is an object that consists of the pathname and state properties. The pathname is determined based on the condition, and the state object contains the desired state to be passed to the target URL.
When you click on the link, React Router will handle the navigation and update the URL without causing a full page refresh. The new component rendered for the target URL can access the state using the location.state property.
Make sure you have set up the necessary route configurations in your React Router setup to handle the /ecgo-3 and /ecgo-5 URLs and retrieve the state using the location.state object in the destination component.
If you have two separate links that pass different route state, or a single link that conditionally passes different route states, then the routed component that receives the state should handle
location.state
updates during the life of the component, e.g. while it is mounted. Use theuseEffect
hook to "listen" to and handle any changes on thelocation.state
value.Example: