React router, pass data when navigating programmatically?

The current answers are outdated.

React Router 6:

Use the useNavigate hook:

const navigate = useNavigate();
navigate('/other-page', { state: { id: 7, color: 'green' } });

Then, you can access the state data in ‘/other-page’ via the useLocation hook:

const {state} = useLocation();
const { id, color } = state; // Read values passed on state

React Router 4 or 5:

Call history.push, and pass an object as the 2nd param to pass state:

props.history.push('/other-page', { id: 7, color: 'green' }))

Then, you can access the state data in ‘/other-page’ via:

props.location.state

Leave a Comment