Fix "cannot read properties of undefined (reading map)" in JS
The "Uncaught TypeError: Cannot read properties of undefined (reading 'map')" error occurs in JavaScript, whenever you try to use the array map
method on a variable that is undefined
. This can usually happen in React, whenever you need to loop through an array of elements and display them.
{posts.map(post => <Card details={post} />)}
However, the array on which you are executing the map
is undefined
. This means that JavaScript sees the following code, and throws the above error:
// Trying to run map on undefined
{undefined.map(post => <Card details={post} />)}
// Or simply try to run in your console
undefined.map()
Try to run the above code in your console, and you will end up with the very same error. This is a common pitfall that can be easily avoided using the following solution.
How to Fix the Error?
In order to fix the error, you need to make sure that the array is not undefined
. In order to do this, the simplest way is to use optional chaining.
{posts?.map(post => <Card details={post} />)}
You can use optional chaining by introducing a question mark after the variable. You can also use a logical AND, or use an if
check prior to rendering to prevent running into issues.
// Using logical AND
{posts && posts.map(post => <Card details={post} />)}
// Using an if check
if (!posts) {
return null
}
// Here post will not be undefined anymore
return (
<React.Fragment>
{posts.map(post => <Card details={post} />)}
</React.Fragment>
)
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: