Last updated: Jan 16, 2023
Reading timeยท2 min
To solve the error "export 'Redirect' (imported as 'Redirect') was not found
in 'react-router-dom'", use the Navigate
component instead of Redirect
, e.g.
<Navigate to="/dashboard" replace={true} />
.
The Navigate
component changes the current location when it's rendered.
import React from 'react'; // ๐๏ธ import Navigate instead of Redirect import {Navigate} from 'react-router-dom'; export default function App() { const user = {id: 1, name: 'James Doe'}; return ( <div> {user && <Navigate to="/dashboard" />} </div> ); }
In version 6 of React Router, the Redirect
component is replaced with
Navigate
.
Navigate
component is rendered, it changes the current location.The component is a wrapper for the useNavigate
hook which enables us to
navigate programmatically.
// ๐๏ธ import useNavigate import {useNavigate} from 'react-router-dom'; export default function App() { const navigate = useNavigate(); const handleClick = () => { // ๐๏ธ navigate programmatically navigate('/about'); }; return ( <div> <button onClick={handleClick}>Navigate to About</button> </div> ); }
You can also pass the Navigate
component as the element
prop of a Route
.
import React from 'react'; import { Navigate, Route, Routes, } from 'react-router-dom'; export default function App() { return ( <div> <Routes> <Route path="/" element={<Navigate to="dashboard" />} /> </Routes> </div> ); }
The Navigate
component also takes a replace
prop which allows us to replace
the current entry in the history stack.
import React from 'react'; // ๐๏ธ import Routes instead of Switch ๐๏ธ import {Navigate} from 'react-router-dom'; export default function App() { const user = {id: 1, name: 'James Doe'}; return ( <div> {user && <Navigate to="/dashboard" replace={true} />} </div> ); }
When the replace
prop is set to true
, the current entry in the history stack
gets replaced with the new one.
This is useful, for example, when a user logs in - you don't want them to be able to click the back button and get back to the login page.
Or if you have a route that redirects to a different page. Then you don't want users to click the back button and get redirected again.