240

I am getting the following error when running npm run start in the terminal.

Attempted import error: 'Redirect' is not exported from 'react-router-dom'.

I have reinstalled node_modules, react-router-dom, react-router. Also restarted the terminal and my computer, but the issue persists.

My code:

import React from 'react';
import { Switch, Redirect } from 'react-router-dom';

import { RouteWithLayout } from './components';
import { Minimal as MinimalLayout } from './layouts';

import {
  Login as LoginView,
  Dashboard as DashboardView,
  NotFound as NotFoundView
} from './views';

const Routes = () => {
  return (
    <Switch>
      <Redirect
        exact
        from="/"
        to="/dashboard"
      />
      <RouteWithLayout
        component={routeProps => <LoginView {...routeProps} data={data} />}
        exact
        layout={MinimalLayout}
        path="/login"
      />
      <Redirect to="/not-found" />
    </Switch>
  );
};

export default Routes;

Here is my package.json imports:

"react-router": "^6.0.0-beta.0",
"react-router-dom": "^6.0.0-beta.0",
Sebastian Nielsen
  • 3,835
  • 5
  • 27
  • 43
Zero Cool
  • 2,541
  • 2
  • 8
  • 13
  • 8
    To keep everyone on their toes, react-router breaks compatibility with everything every now and then ;) – Evert Nov 19 '21 at 18:54

14 Answers14

362

For react-router-dom v6, simply replace Redirect with Navigate

import { Navigate } from 'react-router-dom';
.
.
.
{ component: () => <Navigate to="/404" /> }
ritz
  • 4,747
  • 2
  • 15
  • 13
  • 1
    The [Navigate](https://reactrouter.com/en/main/components/navigate) documentation says it's a wrapper around [useNavigate](https://reactrouter.com/en/main/hooks/use-navigate), whose doc page says "Important: It's usually better to use [redirect](https://reactrouter.com/en/main/fetch/redirect) in loaders and actions than this hook". That's all for main(6.4.3). So are those doc bugs? – Sigfried Nov 09 '22 at 16:47
  • @Sigfried `redirect` documentation says that it is equivalent to changing the route with 302 status. So it can't be used for navigating the application. – ritz Nov 09 '22 at 20:15
  • Thanks. Using was bothering me while trying to debug some other problem and the component that (sometimes) returned was re-rendering once or twice before the url changed. Anyway, I fixed the bug, sweeping the annoyance under the rug. – Sigfried Nov 10 '22 at 21:46
97

Redirect has been removed from v6. You can replace Redirect with Navigate.

import {
  BrowserRouter as Router,
  Routes,
  Route,
  Navigate,
} from 'react-router-dom';
import Home from '../home/Home';

export default function App() {
  return (
    <Router>
      <Routes>
        <Route path="/home" element={<Home />} />
        <Route path="/" element={<Navigate replace to="/home" />} />
      </Routes>
    </Router>
  );
}
Onkar Kole
  • 1,197
  • 7
  • 13
38

Redirect component has been removed from the react-router version 6.

From react router docs:

The <Redirect> element from v5 is no longer supported as part of your route config (inside a ). This is due to upcoming changes in React that make it unsafe to alter the state of the router during the initial render. If you need to redirect immediately, you can either a) do it on your server (probably the best solution) or b) render a <Navigate> element in your route component. However, recognize that the navigation will happen in a useEffect.


If you want to use Redirect component, you will have to use react router version 5.

Alternatively, you can use Navigate component from react router v6. A <Navigate> element changes the current location when it is rendered

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

return (
  <Navigate to="/dashboard" replace={true} />
)

Note: Navigate is a component wrapper around useNavigate hook. You can use this hook to change routes programmatically.

Yousaf
  • 27,861
  • 6
  • 44
  • 69
  • 4
    Alternative to `Redirect` in react-router-dom v 6 is `Navigate`. Example: -- `` to `` Reference Link: https://reactrouter.com/docs/en/v6/api#navigate – Jai Saravanan Nov 25 '21 at 11:58
16

Redirect have been removed from v6 but you can do it like that right now :

<Route path="*" element={<Navigate to ="/" />}/>
Devtrotter
  • 161
  • 1
  • 2
12

You can't use the Redirect component because it has been removed from react-router-dom version 6.

You can use react-router-dom version 4.2.2. Just use the code below to install it.

npm install --save react-router-dom@4.2.2

or

yarn add react-router-dom@4.2.2
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Jaied
  • 900
  • 9
  • 13
11

switch Redirect into Navigate, it will work.

<Route path='/' exact>
   <Navigate to={`/documents/${uuidV4()}`} />
</Route>
Suraj
  • 802
  • 9
  • 7
10

Redirect component has been removed from the react-router version 6, For react-router-dom v6, simply replace Redirect with Navigate

import { Navigate } from 'react-router-dom';

<Routes>
<Route path="/login" element={isLogin ? <Navigate to="/" /> : <Login />}/>
</Routes>
9

In react-router-dom version 5.x.x > 6 we can use <Redirect />

import { Redirect } from 'react-router-dom';

{ component: () => <Redirect to="/dashboard" /> }

In react-router-dom version 5.x.x < 6 we can use <Navigate />

import { Navigate } from 'react-router-dom';

{ component: () => <Navigate to="/dashboard" /> }
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
8

For versions 6.X you must use the hook useNavigate.

piruo7
  • 91
  • 4
5
import {
    Routes,
    Route ,
    Navigate
  } from "react-router-dom";

return (
            <Routes>
                <Route path='/products/:id' element={<Store/>} />

                 //replace Redirect with Navigate
                <Route path="*" element={<Navigate to ="/products" />}/>
            </Routes>

    );
ZygD
  • 22,092
  • 39
  • 79
  • 102
Saye
  • 83
  • 2
  • 7
5

Hi I remembered there was a hook called useHistory, this hook still exist, this only have a few changes and was renamed to useNavigate. Using this and following one of the examples from the documentation, I did this rework for my protected routes:

import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useAuth } from "../../contexts/AuthContext";

function ProtectedRoutes({ component: Component }, props) {
  const [loading, setLoading] = useState(true);

  const { currentUser } = useAuth();
  const navigate = useNavigate();

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

  return <>{loading ? "Loading..." : <Component {...props} />} </>;
}

export default ProtectedRoutes;

And in my Routes this is used like this:

import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import AuthFirebaseHelper from "./helpers/AuthFirebaseHelper/AuthFirebaseHelper";
import ProtectedRoutes from "./helpers/ProtectedRoutes/ProtectedRoutes";
import Dashboard from "./components/Dashboard";
import Home from "./components/Home";

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/authentication" element={<AuthFirebaseHelper />}></Route>
        <Route path="/" exact element={<Home />}></Route>
        <Route
          path="/restricted"
          element={<ProtectedRoutes component={Dashboard} />}
        ></Route>
      </Routes>
    </Router>
  );
}

export default App;

The documentation for useNavigation

Juan Emilio
  • 151
  • 3
  • 5
4

As it is removed in v6, you can use this as an alternative.

<Route path="*" element={<NotFound />} />
Rakesh
  • 158
  • 1
  • 9
0

I wanted to call it from a function, and useNavigate was giving me problems for not being called from a component.

My site uses a context to hold drawers, so that drawers are always written to the same point and can stack if I want them to.

I added another property, commands

if (responseData.page?.url) {
  MyContext.command.make(<Navigate to={responseData.page.url />);
      setTimeout(()=>MyContext.command.clear(), 1500)
}

command.clear() just calls setCommand(null), so I'm able to call this from components and functions alike, without React complaining about it like it does with useNavigate.

Regular Jo
  • 5,190
  • 3
  • 25
  • 47
-2

Actually switch and redirect is the routers defined jn react-router version 5 and currently react-router version 6 so this will not word either You used version 5 with switch and redirect or routers and to with version 6