Home > other >  React version of window.location.replace()?
React version of window.location.replace()?

Time:04-03

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()

CodePudding user response:

import { useNavigate } from 'react-router-dom'    
const navigate = useNavigate()
navigate("/")

Goes to home.

  • Related