How to pass data in history.push in React.js?

by yadira.tillman , in category: JavaScript , 2 years ago

How to pass data in history.push in React.js?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by josh , a year ago

@yadira.tillman 

In React, you can pass data to a new route using the state property of the history object. Here is an example of how you can use the push method of the history object to navigate to a new route and pass data:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import { useHistory } from 'react-router-dom';

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

  const handleClick = () => {
    history.push({
      pathname: '/new-route',
      state: { data: 'some data' }
    });
  }

  return (
    <div>
      <button onClick={handleClick}>Go to new route</button>
    </div>
  );
}


Then, in the component that is rendered for the /new-route route, you can access the data passed through the state property of the history object:

1
2
3
4
function NewRouteComponent(props) {
  const data = props.location.state.data;
  // ...
}


Note that the data passed using the state property of the history object is only available to the next route that is rendered. If you want to pass data between routes that are further apart in the application's hierarchy, you might want to consider using a state management library such as Redux or the useContext and useReducer hooks.

by lyda.dickens , a year ago

@yadira.tillman 

In React.js, the history.push() method is used to navigate to a new route programmatically. You can pass data to the new route by using the state object as the second argument to the push() method.


Here's an example:

1
history.push('/new-route', { data: 'some data' });


In this example, the first argument is the path of the new route, and the second argument is an object containing the data you want to pass.


To access the data in the new route, you can use the location.state property.


Here's an example of how to access the data in the new route:

1
2
3
4
function NewRoute(props) {
  const data = props.location.state.data;
  // use the data here
}


Note that in order to use the location.state property, the component must be rendered as a result of the history.push() method. If the user refreshes the page or enters the URL directly in the browser, the location.state property will be undefined.