user13787463
user13787463

Reputation:

How to change the state of history object in react?

I was trying to modify the entry of the current history object instead of creating a new one but I got this error

history.replace is not a function

Error screenshot

//My attempts were:

import { Switch, Route, Redirect } from 'react-router-dom';


   history.replaceState( position );

   history.replace( null, position );

I'm using version ^16.13.1" of react-router-dom.

Upvotes: 2

Views: 3834

Answers (1)

jdaz
jdaz

Reputation: 6053

react-router uses the history package, so you have to import it.

import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
const position = '/logged-in';
history.replace(position);

With vanilla Javascript, if you just want to update the URL without reloading any components, you can use window.history.replaceState({}, title, position).

Upvotes: 2

Related Questions