Sagar Kharche
Sagar Kharche

Reputation: 2681

How to update the router state on history.replace in react router?

My react router has state isActive(boolean) value. When I use the Link component to redirect to different route I can update the state as follows and its working fine:-

<Link to={{
        pathname: "my-home-page",
        search: '?query=abc',
        state: { isActive: true }
}}>Go to Home</Link>

Also when I use history.push state is updating correctly bu using below code:-

history.push({
               pathname: '/template',
               search: '?query=abc', 
               state: {
                isActive: true
               }
});

However when I am using history.replace in javascript I am not able to update the state. I am trying the below code however its not working.

history.replace({ pathname: 'home', search: '?query=abc', isActive: true});

Anyone knows what I am doing wrong? Why my state is not updating while redirecting with history.replace

Upvotes: 19

Views: 102338

Answers (3)

Shraddha J
Shraddha J

Reputation: 784

history.replaceState(stateObj, title, [url])

or

window.history.replaceState(stateObj, title, [url])

where,

  1. stateObj can be set to null
  2. title can be any title you want to show in browser
  3. url can be window.location.pathname

Upvotes: 1

Yue Qiu
Yue Qiu

Reputation: 131

Try history.replace({ pathname: 'home', search: '?query=abc', state:{isActive: true}});

Upvotes: 13

jorbuedo
jorbuedo

Reputation: 2161

What version of the router is it? In History API, and when I've used it, the first parameter is the pathname (without object, just the string), and the second parameter is the state.

Upvotes: 12

Related Questions