Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to redirect in react if the user logged in

Well before writing this question i have searched internet Basically it shows 3 solution i tried all they seems to be outdated

1. using history.push('/')

The problem i am facing with this method is that browser saying who the hell is push i dont know what she is to debug i try to console history i find it is undefined i have seen in the answer they

I am just copying their answers

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import { useHistory } from "react-router-dom"

function HomeButton() {
  let history = useHistory()

  function handleClick() {
    history.push("/home")
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  )
}

but this does not work because useHistory import error it is outdated the other answers also is not usable like done with redirect again having import error

Please suggest me a good way to do this

>Solution :

history is depreciated since react-router version 6+, if you want to migrate then follow this link.

If you however freshly installed version 6+ then you can use useNavigate

import { useNavigate } from "react-router-dom";

function HomeButton() {
  let navigate = useNavigate()

  function handleClick() {
     navigate("/home")
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  )
}

more on the topic here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading