Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the alternative for Redirect in react-router-dom v 6.0.0?

New version of react-router-dom (v6.0.0) doesn't identify "Redirect". What is the alternative for it?

like image 960
Ali Nematollahi Avatar asked Nov 14 '21 09:11

Ali Nematollahi


People also ask

What can I use instead of redirect in react router?

Redirect and Navigate Component With the release of React Router v6, the Redirect component was removed and replaced with the Navigate component, which operates just as the Redirect component does by taking in the to prop to enable you redirect to the page you specify.

What is the best way to redirect a page using react router?

To redirect to another page on button click in React: Use the useNavigate() hook, e.g. const navigate = useNavigate(); . Call the navigate() function, passing it the path - navigate('/about') .


2 Answers

Redirecting alone is done via the Navigate component with the replace prop specified.

<Navigate replace to="/" />

If you want to replicate RRDv5's Redirect component redirecting from a path then you need to combine with a Route.

<Route path="/somePath" element={<Navigate replace to="/" />} />
  • Navigate
  • Routes & Route
like image 118
Drew Reese Avatar answered Nov 15 '22 05:11

Drew Reese


If you aren't server rendering your app you can still redirect on the initial render in the client like this:

import { Routes, Route, Navigate } from "react-router-dom";

    function App() {
      return (
        <Routes>
          <Route path="/home" element={<Home />} />
          <Route path="/" element={<Navigate replace to="/home" />} />
        </Routes>
      );
    }

In the above example, when someone visits /, they will automatically be redirected to /home, same as before.

Please note however that this won't work when server rendering because the navigation happens in a React.useEffect().

Have a look at Redirects in React Router v6 for some deeper details.

like image 29
zerocewl Avatar answered Nov 15 '22 04:11

zerocewl