I am using React Router hooks for navigation useHistory
.
Navigate : history.push("/home", { update: true });
In home : I am trying to get params let {update} = useParams();
But update
is always undefined. Whats wrong with this code. Any suggestions ?
In react router v. 6, useHistory doesn't exist anymore, instead we have a useNavigate hook. This useNavigate hook gives us a navigate object and function, and this navigate function can be executed to navigate somewhere else.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With