Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React version of window.location.replace()?

As an example, I have this in code for my login button.

var rJson = JSON.parse(request.responseText);
        if (rJson.success) {
          console.log("login success");
          window.location.replace(redirectLink);
          }

Works just fine, but I feel like there has to be a way to achieve the same thing in something from react-router-dom, similar to how

  <Link to="/fooPage" style={{ textDecoration: "none" }}>
    <Button>
      Foo
    </Button>                
  </Link>

would load the new page in, but not reload the entire window, and with things like my log-in button, I feel like it would be preferable to load the page via the react-router-dom, vs reloading the entire window. I hope that makes sense. Everything I found in the react documentation had more to do with using redirects in the HTML portion of a component that gets rendered out, like , vs redirecting the user in code, using window.location.replace()

like image 888
Joesph Stah Lynn Avatar asked Nov 28 '25 13:11

Joesph Stah Lynn


1 Answers

The equivalent to window.location.replace would be

import { useNavigate } from 'react-router-dom'

const navigate = useNavigate()
navigate('/new-path', {replace: true})

Without replace: true instead of replacing the new location, it assigns it. Meaning, when the user clicks the back button, it would go to the path where they were redirected from.

Side note

From react-router useNavigate docs:

It's usually better to use redirect in loaders and actions than this hook

So for protected routes, etc. it would be better to use redirect

like image 117
Kaspar Püüding Avatar answered Dec 01 '25 09:12

Kaspar Püüding



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!