How to fix error “Cannot read property ‘pathname’ of undefined” in React

Cannot read property ‘pathname’ of undefined in React

If you don’t know how to fix the error “Cannot read property ‘pathname’ of undefined” in React, don’t worry. We will give you some solutions in this article. Read on it.

The cause of the error

As far as I know, this error can be caused by one of two main reasons that the Link tag of React Router has not been defined props to, so when we select the Route, and the program runs to the Link tag but we do not see it. Link’s destination, the program will report props to undefined.

The second possible reason for this error is that you are using React Router version of less than 4. x.x. The program has not been upgraded to handle errors like this. You can read the next part of the article to learn how to handle and fix this error.

Solving the error “Cannot read property ‘pathname’ of undefined” in React

You can see the package.json file below to know why the error “Cannot read property ‘pathname’ of undefined” in React occurs.


"dependencies": { 
"react": "^15.5.4", 
"react-dom": "^15.5.4", 
"react-router": "^2.0.0", 

This is a common cause of this error. Let’s see some ways to fix this error below and give yourself the answer.

Updating history method

The history library makes it simple to manage session history wherever JavaScript runs. Using a history object’s minimal API, you can manage the history stack, navigate, and save the state between sessions. Additionally, the differences between environments are eliminated.


npm install history@latest --save

Because this is an error that can occur when the library version is too old to match the syntax, the error is also fixed when we update to the latest version.

Setting “to” props for <Link> method

This error can also be caused when you don’t set the “to” attribute for the Link tag in React Router. We can fix this by adding the path for the Link tag.


// Change to
<Link to=”#”>Home</Link>

Or you can also set the value to undefined so that the program can know that your Link has been set “to” props and will avoid the error. I hope these methods will be helpful to you.


To summarize, there are many ways to solve the error “Cannot read property ‘pathname’ of undefined” in React. After reading this article, we know some simple ways, like updating the history method or setting “to” props for <Link> method. Let’s try two methods. Good luck to you!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *