Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send params in useHistory of React Router Dom?

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 ?

like image 724
Kais Avatar asked Dec 24 '19 05:12

Kais


People also ask

What can I use instead of useHistory in react?

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.


Video Answer


1 Answers

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;
like image 145
wentjun Avatar answered Sep 22 '22 17:09

wentjun