Batuhan Baybaş
Batuhan Baybaş

Reputation: 23

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

Upvotes: 0

Views: 2872

Answers (2)

Drew Reese
Drew Reese

Reputation: 202706

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.json file entry for react-router-dom is correct then you may just have forgotten to run npm install to install the dependencies.

    Run npm i to install the project's dependencies.

  • If the package.json specifies a different version of react-router-dom then you'll need to uninstall that version and install v6.

    1. Uninstall current version, and also any version of react-router and history (to remove any compatibility issues since v6 uses history@5)

      npm uninstall -s react-router react-router-dom history

    2. Install react-router-dom v6

      npm install -s react-router-dom@6

Upvotes: 0

Charles Kasasira
Charles Kasasira

Reputation: 320

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;

Upvotes: 2

Related Questions