A common scenario where this error occurs is when we work with API response data. When we expect an array from the API response and made a map function in the response data, API sent other datatypes leading to the above error. So this data needs to be checked and confirm it is an array and parsed accurately within our React app.
We can avoid the error by conditionally checking whether the value is an array or not using the
Array.isArray
method. The Array.isArray() is a static method that determines whether the passed value is an Array or not. The Array.isArray() method returns
true
if the value is an Array and otherwise, it returns
false
. It does not check the value's prototype chain. It returns
true
for a value that created using the array literal syntax or the Array constructor.
return
(
<>
{Array.isArray(data.products) ? data.products.map(element => {
return
<
h2
key
=
{element}
>
{element}
</
h2
>
;
}) : ''}
}
Here we checked variable is an array or not using
Array.isArray
method. If it is not an array, then we can return an empty value.
If we have an array-like object and we are trying to convert it to an array, then use the Array.from() method before calling the map method. And If we are trying to iterate over an object, use the
Object.values()
method to get an array of the values on which you can call the map() method as given below.
import React from 'react';
export default function App() {
const data = {
vehicle:"car",
color:"red",
price:1000
return (<>
{Object.values(data).map(element => {
return <h2 key={element}>{element}</h2>;
}
The Object.values() method returns an array of a given object's property values.
Conclusion
To solve “TypeError: map() is not a function” in React, make sure we are calling the map function in an array in which the .map function is only available. Use Array.isArray method to conditionally check the value in the variable is an array or not before applying the map function.
Get the Mouse Position (coordinates) in React
Warning: The tag is unrecognized in this browser
Cannot read property of undefined in JavaScript
Too many re-renders. React limits the number of renders to prevent an infinite loop
Get the current route using React Router
How to Integrate Custom Build CKEditor5 with React
Pass data from child to parent component in React
node: --openssl-legacy-provider is not allowed in NODE_OPTIONS
Only expressions, functions or classes are allowed as the default export
Explore All Blogs