marek
marek

Reputation: 57

How to render array passed to sub element in React JS?

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

Answers (1)

alexpods
alexpods

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:

  1. 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>
            )
        }
    });
    
  2. Use || operator:

    <ul className="Uli">
        {(this.props.data || []).map(function(value) {
            return <li key={value}>{value}</li>
        })}
    </ul>
    
  3. Prevent ULi rendering, if does not belongsto is undefined:

    {this.state.data.belongsto && <Uli data={this.state.data.belongsto}/>}
    

Upvotes: 4

Related Questions