Reputation: 2928
Here is whats inside my tbody
tag:
{this.props.listingData.map((listingData,index) =>
<tr key={index}>
<td>{listingData.location_id}</td>
<td>{listingData.location}</td>
<td>{listingData.description}</td>
</tr>
)}
I'm getting map of undefined
error.
Tried logging this.props.listingData
& it works.
Here is sample map
data which I used:
[{"location_id":1,"location":"HKG","description":"Hong Kong","update_by":null,"update_time":null,"create_by":null,"create_time":null,"rec_state":0},{"location_id":2,"location":"KUL","description":"Kuala Lumpur","update_by":null,"update_time":null,"create_by":null,"create_time":null,"rec_state":0}]
Should be working?
My getDefaultProps
:
getDefaultProps() {
return {
//value: 'default value' //called as this.props.value
listingData: [{"location_id":1,"location":"HKG","description":"Hong Kong","update_by":null,"update_time":null,"create_by":null,"create_time":null,"rec_state":0},{"location_id":2,"location":"KUL","description":"Kuala Lumpur","update_by":null,"update_time":null,"create_by":null,"create_time":null,"rec_state":0}]
};
}
Tried this and still getting the error.
Upvotes: 1
Views: 54
Reputation: 1089
You have to define the default props that is a good practice when creating you component, according to the document https://facebook.github.io/react/docs/reusable-components.html#default-prop-values:
var MyComponent = React.createClass({
getDefaultProps: function() {
return {
listingData: []
};
},
render: function () {
//...
}
});
or es2015
class MyComponent extends React.Component {
render() {
//...
}
}
MyComponent.defaultProps = {
listingData: []
}
with static property support
class MyComponent extends React.Component {
static defaultProps = {
listingData: []
};
render() {
//...
}
}
Upvotes: 1
Reputation: 74615
Sounds like you're performing an asynchronous fetch and passing the response as a prop to this component. This means that the first time the component is rendered, it will be undefined (try putting a breakpoint inside render
and see for yourself).
As you've seen, you can't call map
on undefined
, so you need to return something else if you don't have the data yet. Personally I prefer something along these lines:
if (!this.props.listingData) return null;
return this.props.listingData.map(listingData => // ...
There are clearly other ways you can write this. Alternatively, you can provide default props.
Note if location.id
is unique, you should use that as your key
, rather than the loop index.
Upvotes: 0