I have the following component which is being called from a container component. The container component passes the transactions prop.
I know that the data property in prop is being passed in fine and has data and can be accessed from the console.log call. However, when I try to map the data and create the list, I get an error: Cannot read property 'map' of undefined
Here is what the data looks like:
[
{"transid":3426,"acct":"acct1","category":"Auto"},
{"transid":3427,"acct":"acct2","category":"Subscriptions"}
]
What am I doing wrong?
import React from 'react';
export default function TransactionManagerView (props) {
console.log(props.data);
return (
<ul>
{
props.data.map(function(el,index) {
return <li key={index}>{el.category}</li>
})
}
</ul>
)
}
The "Cannot read property 'props' of undefined" error occurs when a class method is called without having the correct context bound to the this keyword. To solve the error, define the class method as an arrow function or use the bind method in the classes' constructor method.
The error Cannot read property 'map' of undefined' is thrown when the map function in the CommentList component is executed. Fix the "Cannot read property 'map' of undefined" Error in React. The variable you are trying to map over is undefined .
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. You can use optional chaining by introducing a question mark after the variable.
Provide a check for undefined prop.data
and then render the component because it is possible that the props initially don't provide the data but is available in the second render. That should solve your problem
class App extends React.Component {
render() {
var data = [
{"transid":3426,"acct":"acct1","category":"Auto"},
{"transid":3427,"acct":"acct2","category":"Subscriptions"}
]
return (
<div ><TransactionManagerView data={data}/></div>
)
}
}
const TransactionManagerView = function(props) {
console.log(props.data);
return (
<ul>
{
props.data && props.data.map(function(el,index) {
return <li key={index}>{el.category}</li>
})
}
</ul>
)
}
ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="app"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With