Home > OS >  React-router-dom throws two errors when reading the pathname property
React-router-dom throws two errors when reading the pathname property

Time:11-07

when I use the routes with react-router-dom 6, I see two different errors:

  1. TypeError: Cannot destructure property 'pathname' of ''undefinded' or 'null'

  2. TypeError: Cannot read properties of undefined (reading 'pathname') and shows me this code from the react-router's file: C:/Users/FAMILIA/Desktop/packages/react-router/index.tsx:281

     let {
     pathname = "/",
     search = "",
     hash = "",
     state = null,
    

what I have tried: installing again react-router-dom, updating the history dependency to the version 5.1.0

this is my code:

import { Router, Routes, Route, Link, NavLink } from 'react-router-dom'
import Home from './views/Home.jsx';

function App() {
  return (
    <Router>
      <div>
        <Link to="/home">Home</Link>
      </div>
      <Routes>
        <Route path="/home" element={<Home/>}/>
      </Routes>
    </Router>
  );
}

export default App;

these are the dependencies of the package.json

history
"dependencies": {
    "@craco/craco": "^6.4.0",
    "@testing-library/jest-dom": "^5.15.0",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "history": "^5.1.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-router-dom": "^6.0.0",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.1.2"
  }

CodePudding user response:

Version 6 of react-router-dom has some pretty significant breaking changes from previous versions.

It's not common to use the Router import from react-router-dom though, even in version 4/5, you'd typically import one of BrowserRouter, HashRouter, or MemoryRouter over the lower level Router.

The cause of your issue is found Edit react-router-dom-throws-two-errors-when-reading-the-pathname-property

The alternative, OFC, is to just use one of the higher level routers instead.

Example:

import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";

export default function App() {
  return (
    <Router>
      <div>
        <Link to="/home">Home</Link>
      </div>
      <Routes>
        <Route path="/home" element={<Home />} />
      </Routes>
    </Router>
  );
}

CodePudding user response:

I found a solution. Installing a previous version of the react-router-dom. I think is a new error, so I think a lot of people will have the same conflict with the last version of react.

  • Related