javascriptreactjsreact-routerreact-router-dom

Cannot load file './dom' from module 'react-router' - React router dom


I have installed latest react router dom and in package.js its showing "react-router-dom": "^7.0.2".and when i check npm -v react-router-dom its showing 10.9.0. And in my code

import React from "react";
import ReactDOM from "react-dom";
import Header from "./components/Header";
import Body from "./components/Body";
import About from "./components/About";
import {
  createBrowserRouter as Router,
  RouterProvider
} from "react-router-dom";

const AppLayout = () => {
  return (
    <div className="app">
      <Header />
      <Body />
    </div>
  );
};

const appRouter= createBrowserRouter ([
  { path: "/", element: <AppLayout /> },
  { path: "about", element: <About /> },
])

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<RouterProvider router= {appRouter} />);

I am getting and error like

@parcel/core: Failed to resolve 'react-router/dom' from './node_modules/react-router-dom/dist/index.mjs' D:\Namsthe\node_modules\react-router-dom\dist\index.mjs:13:48 12 | // index.ts

13 | import { HydratedRouter, RouterProvider } from "react-router/dom"; | ^^^^^^^^^^^^^^^^^^ 14 | export * from "react-router"; 15 | export { @parcel/resolver-default: Cannot load file './dom' from module 'react-router'


Solution

  • React-Router 7 really changed things up how they organize their code. The RouterProvider component is not exported from react-router-dom, it comes from a more deeply nested package, the platform-specific, e.g. DOM-specific, react-router/dom. In v7, react-router is the primary entry point.

    1. Uninstall react-router-dom: npm un react-router-dom

    2. Install react-router: npm i react-router@latest

    3. Update the import to be from react-router

      import {
        createBrowserRouter as Router,
        RouterProvider
      } from "react-router";
      

    For complete details see: