mo akh
mo akh

Reputation: 11

change value of this.props.location.state in react route

There are many examples on the Internet that look like the following code:

const { state } = this.props.location;
    window.location = state ? state.from.pathname : "/dashboards/index";

how can i change this.props.location.state in source class and pass to destination ?

My question is if I want to go from one page (class component) to another using route, how can I change the value of this.props.location.state and pass it to the destination component? My scenario is that when someone enters a protected page, and redirects to the login page then returns to the requested page after authentication. by change value of this.props.location.state?

Upvotes: 0

Views: 4396

Answers (2)

Blatzo
Blatzo

Reputation: 166

I am not sure what you are asking but as much as I think, you want to add state while pushing to a route. If that's the case, then this should work in class components

this.props.history.push({
  pathname: '/template',
  search: '?query=something',
  state: { key: value }
})

And in functional components you can use hooks, useHistory

const { push } = useHistory();

push(path, [state])

And you can access the state you just passed in the destination route as
in class components

this.props.location.state.key

in functional components

const { state }  = useLocation();

state.key

Upvotes: 3

Shravan Dhar
Shravan Dhar

Reputation: 1560

Don't mutate this object. You're not supposed to !!

If you want to redirect between pages then you can use:

this.props.history.push("/path-to-navigate")

Upvotes: 0

Related Questions