In this article, we will see how to pass the data between multiple components while navigating programmatically using the react router.

Using the push method of an history object we can push the new URL that we want to navigate to and the data along with it.

Following is the example:

import { useHistory } from 'react-router-dom';

function MyComponent() {
  const history = useHistory();

  const handleButtonClick = () => {
    const data = { /* Data to pass */ };
    history.push('/route', data);
  };

  return (
    <button onClick={handleButtonClick}>Navigate to route with data</button>
  );
}

Explanation

In the above example, we define a handleButtonClick function that will be called when the button is clicked.

Inside the handleButtonClick function, we create an object data that contains the data we want to pass to the new route. We then call the push method of the history object, passing in the URL of the new route and the data object.

When the user clicks the button, they will be navigated to the new route, and by using the location prop the ‘data‘ object will be available to the new route.

Following is the example of how to access the passed data in new route.

import { useLocation } from 'react-router-dom';

function MyOtherComponent() {
  const location = useLocation();
  const data = location.state;

  return (
    <div>
      {/* Use the passed data */}
    </div>
  );
}

Using the useLocation() hook we access to the data by using the state property of the location object.

Categorized in:

Tagged in: