简体   繁体   中英

useHistory: Module not found: Can't resolve 'react-router-dom'

I have this project and this project is an ECommerce project, and in this project there is a Navbar, and in Navbar there are three items, "Home, Groups, Shopping", the problem is that when I click on "home" it takes me to the home page, and when it's done Clicking on "groups" will take me to the groups page, as well as for the shop

And for this thing, I used usehistory and

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

but I got this error:

Module not found: Can't resolve 'react-router-dom'

I also used this instruction

"import { useHistory } from "react-router";" 

and got this error:

Module not found: Can't resolve 'react-router-dom'

How can I solve the problem?

package.json:

{
  "name": "c-cart-front-end",
  "version": "1.0.0",
  "description": "",
  "private": true,
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "next"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@apollo/client": "^3.5.6",
    "@apollo/react-ssr": "3.0.0",
    "@firebase/app": "^0.6.18",
    "@types/react-slick": "^0.23.4",
    "@types/react-sticky-el": "^1.0.2",
    "@types/reactstrap": "^8.4.1",
    "@zeit/next-css": "^1.0.1",
    "@zeit/next-sass": "^1.0.1",
    "@zeit/next-typescript": "^1.1.1",
    "animate.css": "^3.7.2",
    "apollo-boost": "^0.4.7",
    "bootstrap-scss": "^4.4.1",
    "deepmerge": "^4.2.2",
    "firebase": "^8.3.2",
    "graphql": "^14.6.0",
    "i18next": "^19.3.4",
    "i18next-browser-languagedetector": "^4.0.2",
    "isomorphic-unfetch": "^3.0.0",
    "jimp": "^0.9.3",
    "js-cookie": "^3.0.1",
    "next": "^12.0.4-canary.4",
    "next-compose-plugins": "^2.2.0",
    "next-fonts": "^1.0.3",
    "next-images": "^1.8.4",
    "nprogress": "^0.2.0",
    "react": "^17.0.2",
    "react-apexcharts": "^1.3.9",
    "react-content-loader": "^5.0.1",
    "react-countdown": "^2.3.1",
    "react-dom": "^17.0.2",
    "react-fullpage": "^0.1.19",
    "react-helmet": "^6.1.0",
    "react-helmet-async": "^1.2.2",
    "react-hook-form": "^6.8.6",
    "react-i18next": "^11.3.4",
    "react-image": "^2.2.2",
    "react-image-lightbox": "^5.1.1",
    "react-input-range": "^1.3.0",
    "react-intl": "^4.3.1",
    "react-masonry-css": "^1.0.14",
    "react-messenger-customer-chat": "^0.8.0",
    "react-multi-carousel": "^2.5.0",
    "react-paypal-button": "^4.1.1",
    "react-responsive-carousel": "^3.1.51",
    "react-reveal": "^1.2.2",
    "react-slick": "^0.25.2",
    "react-sticky-el": "^1.1.0",
    "react-tabs": "^3.1.2",
    "react-toastify": "^5.5.0",
    "reactstrap": "^8.4.1",
    "responsive-loader": "^1.2.0",
    "rxjs-compat": "^6.5.4",
    "sass": "^1.45.1"
  }
}

This file contains the navbar in the project with the elements inside it

import React, { useState, useEffect } from "react";
import Link from "next/link";
import { MENUITEMS } from "../../constant/menu";
import { Container, Row } from "reactstrap";
import { useTranslation } from "react-i18next";
import { useRouter } from "next/router";
import { useHistory } from "react-router";

const NavBar = () => {
  const history = useHistory();
  const { t } = useTranslation();
  const [navClose, setNavClose] = useState({ right: "0px" });
  const router = useRouter();

  useEffect(() => {
    if (window.innerWidth < 750) {
      setNavClose({ right: "-410px" });
    }
    if (window.innerWidth < 1199) {
      setNavClose({ right: "-300px" });
    }
  }, []);

  const openNav = () => {
    setNavClose({ right: "0px" });
    if (router.asPath == "/layouts/Gym")
      document.querySelector("#topHeader").classList.add("zindex-class");
  };

  const closeNav = () => {
    setNavClose({ right: "-410px" });
    if (router.asPath == "/layouts/Gym")
      document.querySelector("#topHeader").classList.remove("zindex-class");
  };

  const [mainmenu, setMainMenu] = useState(MENUITEMS);

  useEffect(() => {
    const currentUrl = location.pathname;
    MENUITEMS.filter((items) => {
      if (items.path === currentUrl) setNavActive(items);
      if (!items.children) return false;
      items.children.filter((subItems) => {
        if (subItems.path === currentUrl) setNavActive(subItems);
        if (!subItems.children) return false;
        subItems.children.filter((subSubItems) => {
          if (subSubItems.path === currentUrl) setNavActive(subSubItems);
        });
      });
    });
  }, []);

  const setNavActive = (item) => {
    MENUITEMS.filter((menuItem) => {
      if (menuItem != item) menuItem.active = false;
      if (menuItem.children && menuItem.children.includes(item))
        menuItem.active = true;
      if (menuItem.children) {
        menuItem.children.filter((submenuItems) => {
          if (submenuItems.children && submenuItems.children.includes(item)) {
            menuItem.active = true;
            submenuItems.active = false;
          }
        });
      }
    });

    setMainMenu({ mainmenu: MENUITEMS });
  };

  const status = (title) => {
    switch (title) {
      case "home":
        return "http://localhost:3000";
      case "collections":
        return "/page/collection";

      default:
        return "http://localhost:3000";
    }
  };

  function handleClickHome() {
    history.push("http://localhost:3000");
  }

  function handleClickCollections() {
    history.push("/page/collection");
  }

  function handleClickShops() {
    history.push("/page/collection");
  }

  return (
    <div>
      <div className="main-navbar">
        <div id="mainnav">
          <div className="toggle-nav" onClick={openNav.bind(this)}>
            <i className="fa fa-bars sidebar-bar"></i>
          </div>
          <ul className="nav-menu" style={navClose}>
            <li className="back-btn" onClick={closeNav.bind(this)}>
              <div className="mobile-back text-right">
                <span>Back navbar</span>
                <i className="fa fa-angle-right pl-2" aria-hidden="true"></i>
              </div>
            </li>
            {/* {MENUITEMS.map((menuItem, i) => { */}
            {/* return ( */}
            <li
            // key={i}
            // className={` ${menuItem.megaMenu ? "mega-menu" : ""}`}
            >
              {/* <a className="nav-link" onClick={(e) => console.log("Hi")}>
                    {" "}
                    {t(menuItem.title)}
                  </a> */}
              <a
                className="nav-link"
                style={{ color: "red" }}
                onClick={handleClickHome}
              >
                {" "}
                {t("Home")}
              </a>
            </li>

            <li>
              <a className="nav-link" onClick={handleClickShops}>
                {" "}
                {t("Shop")}
              </a>
            </li>
            <li>
              <a className="nav-link" onClick={handleClickCollections}>
                {" "}
                {t("Collections")}
              </a>
            </li>
          </ul>
        </div>
      </div>
    </div>
  );
};

export default NavBar;

I solved the problem through these instructions:

import { useRouter } from "next/router";

const router = useRouter();

  function handleClickHome() {
    router.push("http://localhost:3000");
  }

  function handleClickCollections() {
    router.push("/page/collection");
  }

  function handleClickShops() {
    router.push("/page/collection");
  }


 return (
    <div>
      <div className="main-navbar">
        <div id="mainnav">
          <div className="toggle-nav" onClick={openNav.bind(this)}>
            <i className="fa fa-bars sidebar-bar"></i>
          </div>
          <ul className="nav-menu" style={navClose}>
            <li className="back-btn" onClick={closeNav.bind(this)}>
              <div className="mobile-back text-right">
                <span>Back navbar</span>
                <i className="fa fa-angle-right pl-2" aria-hidden="true"></i>
              </div>
            </li>
            <li>
              <a
                className="nav-link"
                style={{ color: "red" }}
                onClick={handleClickHome}
              >
                {" "}
                {t("Home")}
              </a>
            </li>

            <li>
              <a className="nav-link" onClick={handleClickShops}>
                {" "}
                {t("Shop")}
              </a>
            </li>
            <li>
              <a className="nav-link" onClick={handleClickCollections}>
                {" "}
                {t("Collections")}
              </a>
            </li>
          </ul>
        </div>
      </div>
    </div>
  );

Well, just like the error says, you don't have react-router-dom installed. Just run npm install --save react-router-dom .

You also need to use:

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

I think your react-router-dom package module is v6 if you install at the moment, so you have to use useNavigate instead of useHistory , see more: useNavigate() in react-router v6

// This is a React Router v6 app
import { useNavigate } from "react-router-dom";

function App() {
  let navigate = useNavigate();
  function handleClick() {
    navigate("/home");
  }
  return (
    <div>
      <button onClick={handleClick}>go home</button>
    </div>
  );
}

'useHistory' is depreciated in V6 of react-router. You can use 'useNavigate' or 'Navigate' for doing the same thing.

if you use 'useNavigate' the code would be--

import { useNavigate } from 'react-router-dom'
const FileName = () => {
return (
<>
const navigate = useNavigate();
<li  
   onClick={()=>{navigate("/path");}}>
      'link-name'        
 </li> 
 </> 
  )
}

And if you use 'Navigate' the code would be--

import { Navigate } from 'react-router-dom';
const FileName= () => {

const[goToHome, setGoToHome] = React.useState(false);
if(goToHome){
return <Navigate to = "/Home" />;
}
return (
<>
<li 
 onClick={()=>{setGoToHome(true);}}>
   Home
</li >
</> 
 )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM