Home > database >  Unable to install the "useHistory" in React
Unable to install the "useHistory" in React

Time:10-27

I am doing a google clone (mini project) for that I need to import useHistory from react-router-dom.

I have followed the below steps:

step 1: npm install --save react-router-dom (I used this command in terminal) step 2: import { useHistory } from "react-router-dom" (use this in the top of my file) step 3: const history = useHistory() (use this in my code)

after following this steps I am getting the below error:

export 'useHistory' (imported as 'useHistory') was not found in 'react-router-dom' (possible exports: AbortedDeferredError, Await, BrowserRouter, Form, HashRouter, Link, MemoryRouter, NavLink, Navigate, NavigationType, Outlet, Route, Router, RouterProvider, Routes, ScrollRestoration, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, UNSAFE_DataStaticRouterContext, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, UNSAFE_enhanceManualRouteObjects, createBrowserRouter, createHashRouter, createMemoryRouter, createPath, createRoutesFromChildren, createRoutesFromElements, createSearchParams, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, renderMatches, resolvePath, unstable_HistoryRouter, useActionData, useAsyncError, useAsyncValue, useFetcher, useFetchers, useFormAction, useHref, useInRouterContext, useLinkClickHandler, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes, useSearchParams, useSubmit)

It seems like useHistory is not a part of react-router-dom.

Unable to import the useHistory in the react app.

CodePudding user response:

If you are using react-router-dom@6 then the useHistory hook was replaced by the useNavigate hook.

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

...

const navigate = useNavigate();

...

navigate(target);                    // replaces history.push(target)
navigate(target, { replace: true }); // replaces history.replace(target)

If you specifically want or need to use the useHistory hook then you'll need to install the previous react-router-dom version.

npm i -s react-router-dom@5

CodePudding user response:

You can try following steps:

  • Install react router dom. npm install --save react-router-dom.
  • Import the history package from react router dom. import { useHistory } from "react-router-dom"
    
  • Assign the history function to a variable (not necessary but. recommended)
    
  • Use the push() function to redirect the user after a successful login.
  • Related