Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Josh Post
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 uses to a different page - you don't want users to click the back button and get redirected again.