'React router dom problen
I tried to create a protected route and I created a component like this
import {useSelector} from "react-redux";
import {userSelect} from "../../Redux/userSlice";
import {Navigate} from "react-router-dom";
const ProtectedRoute = ({children}) => {
const currentUser = useSelector(userSelect);
if (currentUser.user) {
return children;
}
return <Navigate to="/login"/>;
}
export default ProtectedRoute;
but the problem is Navigate not import from react-router-dom just check docs of router-dom and they recommend and use Navigate for the protected route but it isn't working correctly the main problem is Navigate not import from router-dom for me, my route-dom version is 6.3.0 does anybody know why this has happened and how to solve this import problem ı try to re-install my node_modules files but still not working
Solution 1:[1]
Try using the useNavigate instead
import {useSelector} from "react-redux";
import {userSelect} from "../../Redux/userSlice";
import { useNavigate } from "react-router-dom";
const ProtectedRoute = ({children}) => {
const navigate = useNavigate()
const currentUser = useSelector(userSelect);
if (currentUser.user) {
return children;
}
navigate('/login');
}
export default ProtectedRoute;
Solution 2:[2]
It seems that you don't actually have react-router-dom@6 installed for your project.
You can check the installed version by running npm list react-router-dom` from the project directory.
If the
package.jsonfile entry forreact-router-domis correct then you may just have forgotten to runnpm installto install the dependencies.Run
npm ito install the project's dependencies.If the
package.jsonspecifies a different version ofreact-router-domthen you'll need to uninstall that version and install v6.Uninstall current version, and also any version of
react-routerandhistory(to remove any compatibility issues since v6 useshistory@5)npm uninstall -s react-router react-router-dom historyInstall
react-router-domv6npm install -s react-router-dom@6
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Charles Kasasira |
| Solution 2 | Drew Reese |
