1

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?

2
  • Do you have a getInitialState with an empty belongsto array? Commented Mar 7, 2015 at 14:38
  • data is likely empty the first time if you're loading the data asynchronously. If you just added var data = this.props.data || [] to the render, ... and that works, then it was likely the issue. Commented Mar 7, 2015 at 15:33

1 Answer 1

4

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}/>}
    
Sign up to request clarification or add additional context in comments.

2 Comments

So, I want with the first one and it works fine in firefox :-), that’s great for me. I have just changed it into ` getDefaultProps: function() { return { data: [] } },` (Of course, without understanding)
Is there "a proper one" option to chose from four answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.