How to use Redirect in React react-router-dom v5?

Sometimes, we want to use Redirect in React react-router-dom v5.

In this article, we’ll look at how to use Redirect in React react-router-dom v5.

How to use Redirect in React react-router-dom v5?

To use Redirect in React react-router-dom v5, we call history.push.

For instance, we write

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

function HomeButton() {
  const history = useHistory();

  const handleClick = () => {
    history.push("/home");
  };

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

to call the useHistory hook to return the history object.

Then we call history.push to go to the '/home' URL.

And then we set onClick prop to handleClick to do the redirect when we click the button.

Conclusion

To use Redirect in React react-router-dom v5, we call history.push.