reactjsreact-router

React Router Error: Cannot read properties of undefined (reading 'pathname')


I was attempting to add a Navbar to a Webb app and as soon as I put <Navbar/> into App.js I get the error below. I've read that the error could be related to the to props of <Link/> but I can't find any issues there and I'm having trouble making sense of this error. I appreciate all ideas and thank you for your time!

> components.tsx:197 Uncaught TypeError: Cannot read properties of undefined (reading 'pathname')
    at Router (components.tsx:197:1)

react-dom.development.js:18687 The above error occurred in the component: at Router (http://localhost:3003/static/js/bundle.js:62004:15) at App

Consider adding an error boundary to your tree to customize error handling behavior. Visit https://reactjs.org/link/error-boundaries to learn

Navbar:

export default function Navbar() {
  return (
    <nav className="nav">
      <Link to="/" className="site-title">
        
      </Link>
      <ul>
        <CustomLink to="/reflect">Reflect</CustomLink>
        <CustomLink to="/edi">Edi</CustomLink>
      </ul>
    </nav>
  )
}
  function CustomLink({ to, children, ...props }) {
  const resolvedPath = useResolvedPath(to)
  const isActive = useMatch({ path: resolvedPath.pathname, end: true })
  return (
    <li className={isActive ? "active" : ""}>
      <Link to={to} {...props}>
        {children}
      </Link>
    </li>
  )
}

App.js:

function App() {
  return (
    <>
      <Router>
        <NavBar />
        <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/reflect" element={<Reflect />} />
        <Route path="/edi" element={<Edi />} />
        <Route path="/storyboard" element={<StoryBoard />} />
        <Route path="/texteditor" element={<TextEditor />} />
        <Route path="/*" element={<errorPage />} />
        </Routes>    
      </Router>
       </>
  );
}
export default App;
  

Solution

  • You should not be using <Router>. That requires you instantiate and pass in your own history <Router history={history}>. Use BrowserRouter instead.