How to do a redirect to another route with React Router v6?

Sometimes, we want to do a redirect to another route with React Router v6.

In this article, we’ll look at how to do a redirect to another route with React Router v6.

How to do a redirect to another route with React Router v6?

To do a redirect to another route with React Router v6, we can use the useNavigate hook.

For instance, we write

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

const Comp = () => {
  const navigate = useNavigate();

  const handleClick = () => {
    navigate("/path/to/push");
  };

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

export default Comp;

to call the useNavigate hook to return the navigate function.

Then we create the handleClick function that calls navigate with the path we want to go to.

Then we set onClick to handleClick to go to the path when we click on the button.

Conclusion

To do a redirect to another route with React Router v6, we can use the useNavigate hook.