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.
Code:
"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.
Terminal:
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.
Code:
<Link>Home</Link>
// 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.
Summary
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:
- Module not found: Can’t resolve ‘styled-components’
- Property does not exist on type ‘JSX.IntrinsicElements’
- Property ‘value’ does not exist on type HTMLElement

Hi, my name’s Nathaniel Kirk. I’m interested in learning and sharing knowledge about programming languages. My strengths are C, C++, Python, HTML, CSS, Javascript, and Reactjs. If you have difficulty with them, don’t worry. I’m here to support you.
Name of the university: PTIT
Major: IT
Programming Languages: C, C++, Python, HTML, CSS, Javascript, Reactjs