Reputation: 57
I have simple example with JSON that has array in it. It is loaded with ajax:
{somekey: "value1", somekey2: "value2", belongsto: ["me","you"]}
I can render it by for example:
<div>
belongsto: {this.state.data.belongsto}
</div>
But I would love to render it as list in subcomponent, so I am trying:
<Uli data={this.state.data.belongsto}/>
as:
var Uli = React.createClass({
render: function() {
return (
<ul className="Uli">
{
this.props.data.map(function(value) {
return <li key={value}>{value}</li>
})
}
</ul>
)
}
});
And that gives me:
Uncaught TypeError: Cannot read property 'map' of undefined
How this should be achieved?
Upvotes: 1
Views: 8867
Reputation: 48505
You are loading your json data through AJAX asynchronously, and hence belongsto
is undefined
until you'll got the response from the server.
There are several solutions to solve this:
Add getDefaultProps
method to your ULi component.
var Uli = React.createClass({
getDefaultProps() {
return {
data: []
}
},
render: function() {
return (
<ul className="Uli">
{this.props.data.map(function(value) {
return <li key={value}>{value}</li>
})}
</ul>
)
}
});
Use ||
operator:
<ul className="Uli">
{(this.props.data || []).map(function(value) {
return <li key={value}>{value}</li>
})}
</ul>
Prevent ULi
rendering, if does not belongsto
is undefined
:
{this.state.data.belongsto && <Uli data={this.state.data.belongsto}/>}
Upvotes: 4