Categories
React Answers

How to redirect in React Router v6?

Spread the love

Sometimes, we want to redirect in React Router v6.

In this article, we’ll look at how to redirect in React Router v6.

How to redirect in React Router v6?

To redirect in React Router v6, we can use the navigate function.

For instance, we write

import { useNavigate } from "react-router-dom";
const Comp = () => {
  const navigate = useNavigate();

  useEffect(() => {
    if (loggedIn) {
      return navigate("/");
    }
  }, [loggedIn]);

  //...
};

to call the useNavigate function to return the navigate function.

Then we call navigate with the URL we want to navigate to.

Conclusion

To redirect in React Router v6, we can use the navigate function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to redirect in React Router v6?”

Leave a Reply

Your email address will not be published. Required fields are marked *