Last updated: Apr 7, 2024
Reading timeยท2 min
The error "Cannot read properties of undefined (reading 'pathname')" occurs
when we don't set the to
prop on a Link
component in React Router.
To solve the error, set the to
prop on the Link to the specific path, e.g.
<Link to="/">Home</Link>
.
Here is a minimal example of using the Link component in React Router.
import React from 'react'; // ๐๏ธ import Routes instead of Switch ๐๏ธ import {Route, Link, Routes} from 'react-router-dom'; export default function App() { return ( <div> <div> <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> </ul> </nav> <Routes> <Route path="/about" element={<About />} /> <Route path="/" element={<Home />} /> </Routes> </div> </div> ); } function Home() { return <h2>Home</h2>; } function About() { return <h2>About</h2>; }
If you are getting the error when testing pages that use React router, make
sure to set the location
prop on the Router
component instead of
history
.
import {render} from '@testing-library/react'; import App from './App'; import {Router} from 'react-router-dom'; import {createMemoryHistory} from 'history'; test('renders react component', async () => { const history = createMemoryHistory(); render( <Router location={history.location} navigator={history}> <App />, </Router>, ); // ๐๏ธ Your tests... expect(screen.getByText(/you are home/i)).toBeInTheDocument(); });
If you are trying to access the pathname
, use the
useLocation hook.
import React from 'react'; import {Route, Link, Routes, useLocation} from 'react-router-dom'; export default function App() { // ๐๏ธ with React router const location = useLocation(); console.log('hash', location.hash); console.log('pathname', location.pathname); console.log('search', location.search); return ( <div> <div> <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> </ul> </nav> <Routes> <Route path="/about" element={<About />} /> <Route path="/" element={<Home />} /> </Routes> </div> </div> ); } function Home() { return <h2>Home</h2>; } function About() { return <h2>About</h2>; }
Make sure to wrap your application in a Router
component in your index.js
file.
import {createRoot} from 'react-dom/client'; import App from './App'; import {BrowserRouter as Router} from 'react-router-dom'; const rootElement = document.getElementById('root'); const root = createRoot(rootElement); // ๐๏ธ wrap your App in a Router root.render( <Router> <App /> </Router> );
Router
component is in your index.js
file because that's the entry point of your React application.Once your entire app is wrapped with a Router
component, you can use any of
the hooks from the React router package anywhere in your components.