Pranavan
Pranavan

Reputation: 1395

history.replace in react-router-dom v6

I've previously used react-router-dom v5.2.0. There I used history.replace('/path) to redirect the page to another page. (Hence it will not store in the address history). Now I have to use react-router-dom v6.0.0-beta.0. In version 6, I have to use useNavigate hook instead of useHistory hook. I can use it as below.

const navigate = useNavigate();
navigate('/path')

But I don't know how to use it for redirect. (Like history.replace)

Upvotes: 27

Views: 53041

Answers (2)

hussam alhunaiti
hussam alhunaiti

Reputation: 319

If you trying to replace the current path with another one, you should add ../ before the new path so basically:

navigate("../login", { replace: true })

Upvotes: 8

Ako
Ako

Reputation: 1583

If you need to replace the current location instead of push a new one onto the history stack, use navigate(to, { replace: true }). If you need state, use navigate(to, { state }).

Upvotes: 66

Related Questions