Sometimes, we want to pass data when navigating programmatically with React Router.
In this article, we’ll look at how to pass data when navigating programmatically with React Router.
How to pass data when navigating programmatically with React Router?
To pass data when navigating programmatically with React Router, we can call navigate
with an object.
Then we can use the useLocation
hook to return the object’s data.
For instance, we write
const navigate = useNavigate();
navigate('/other-page', { state: { id: 7, color: 'green' } });
to call navigate
with an object that we want to pass to the component we’re navigating to.
Then in the destination component, we write
const { state } = useLocation();
const { id, color } = state;
to call useLocation
to return an object with the state
property of the object that we passed into navigate
.
Conclusion
To pass data when navigating programmatically with React Router, we can call navigate
with an object.
Then we can use the useLocation
hook to return the object’s data.