1

I am trying to import useNavigate to use it as described in the top response: react button onClick redirect page

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

However, I get this error:

export 'useNavigate' (imported as 'useNavigate') was not found in 'react-router-dom' (possible exports: BrowserRouter, HashRouter, Link, MemoryRouter, NavLink, Prompt, Redirect, Route, Router, StaticRouter, Switch, generatePath, matchPath, useHistory, useLocation, useParams, useRouteMatch, withRouter)

Unlike this post, export 'useNavigation' (imported as 'useNavigation') was not found in 'react-router-dom', I spell useNavigate correctly, so what could be other reasons as to why there is this error?

user19251203
  • 322
  • 4
  • 13
  • 2
    Which version of the router-dom is defined in your package.json ? – Matthieu Riegler Jul 13 '22 at 19:02
  • 2
    It seems you are not using the latest version (v6) of `react-router-dom`. If you are on RRDv5 import and use the `useHistory` hook, otherwise if you want to use the `useNavigate` hook upgrade to `react-router-dom@6`. – Drew Reese Jul 13 '22 at 19:18

1 Answers1

0

The problem is mainly not about how you're importing the import { useNavigate } from "react-router-dom"; Its related to how you're using the module. Since you did not show your full code, Here is how you should correctly use the module.

    // ️ import useNavigate Here instead of useHistory
import {useNavigate} from 'react-router-dom';

export default function WelcomePage() {
  const navigate = useNavigate();

  const handleClick = () => {
    // Now you can navigate programmatically to other urls
    navigate('/login’);
  };
 // Then create a dom element that will be click to navigate 
  return (
    <div>
      <button onClick={handleClick}>Navigate to login page</button>
    </div>
  );
}

I was facing similar error because I was using the module wrongly as useHistory. But the above is how to use it correctly. You can find a step by step way of fixing the error here.

Justice
  • 51
  • 3