Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router: Cannot read property 'pathname' of undefined

I've just started learning React and got stuck at this error.

Uncaught TypeError: Cannot read property 'pathname' of undefined at new Router

Here is my code:

var React = require('react'); var ReactDOM = require('react-dom'); var { Route, Router, IndexRoute } = require('react-router'); var hashHistory = require('react-router-redux')  var Main = require('./components/Main');  ReactDOM.render(     <Router history={hashHistory}>         <Route path="/" component={Main}>          </Route>     </Router>,   document.getElementById('app') ); 

The tutorial I was following uses React-Router 2.0.0, but on my desktop I'm using 4.1.1. I tried searching for changes but was unsuccessful in finding a solution that worked.

"dependencies": { "express": "^4.15.2", "react": "^15.5.4", "react-dom": "^15.5.4", "react-router": "^4.1.1", "react-router-dom": "^4.1.1", "react-router-redux": "^4.0.8" 
like image 507
Alon Avatar asked Apr 25 '17 20:04

Alon


People also ask

How to fix the error 'cannot read property 'pathname' of undefined'?

The error "Cannot read property 'pathname' of undefined" 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.

Why can't I read undefined when testing pages in V6 react router?

See the accepted answer in the following: "Cannot read properties of undefined (reading 'pathname')" when testing pages in the v6 React Router Just make sure that you've added to props to <Link> otherwise you would also get the same error.

What is the difference between react router V5 and V6 API?

The API in React Router v6 has changed from that of v5. See the accepted answer in the following: "Cannot read properties of undefined (reading 'pathname')" when testing pages in the v6 React Router

What is failed prop type in connectedrouter?

Failed prop type: The prop location is marked as required in ConnectedRouter, but its value is undefined. Failed prop type: The prop action is marked as required in ConnectedRouter, but its value is undefined.


1 Answers

I got the above error message and it was extremely cryptic. I tried the other solutions mentioned and it didn't work.

Turns out I accidentally forgot to include the to prop in one of the <Link /> components.

Wish the error message was better. A simple required prop "to" not found or something like that would have been helpful. Hopefully this saves someone else who has encountered the same problem some time.

like image 153
Brennan Cheung Avatar answered Sep 21 '22 21:09

Brennan Cheung