How to send params in useHistory of React Router Dom?
The second parameter in the history.push()
method is actually known as the location state,
history.push(path, [state])
Depending on your requirements, you may want to pass update
as part of the location state, or the query string.
history.push({
pathname: '/home',
search: '?update=true', // query string
state: { // location state
update: true,
},
});
As stated on the React-Router documentation, you can access the state by accessing the location
props. In your case, to get the value for update
,
On class components, assuming that it is connected to the router,
this.props.location
For functional components, you can use the useLocation hook to access the location object.
import { useLocation } from 'react-router-dom';
.
.
const location = useLocation();
console.log(location.state.update) // for location state
console.log(location.search) // for query strings;
This is how you can pass
history.push("/home", { update: true });
and access like this if it's stateless component.
props.location.state.update;
if class based component.
this.props.location.update;
If you are using React Hooks follow this method because this.props is only available in React Class.
Component One:
import React from 'react'
import { useHistory } from "react-router-dom";
const ComponentOne = () => {
const history = useHistory();
const handleSubmit = () => {
history.push('/component-two',{params:'Hello World'})
}
return (
<div>
<button onClick={() => {handleSubmit()}}>Fire</button>
</div>
)
}
Component Two:
import React from 'react'
import { useLocation } from "react-router-dom";
const ComponentTwo = () => {
const location = useLocation();
const myparam = location.state.params;
return (
<div>
<p>{myparam}</p>
</div>
)
}