0

Using React, how do I render a <div> with multiple nested <div>'s inside them? See code below.

var SubTrait = React.createClass({

  render: function() {
    var subTraits = this.props.data;
    return (
    <div className = "subTraitContainer">
      <div>
        { subTraits.forEach(function(subTrait) {
          return (
            <div>
              <h4>{ subTrait.name }</h4>,
              Sub-Sub-Traits
              <SubSubTrait data={ subTrait.children } />
            </div>
          );
        })}
      </div>
    </div>
    );
  }
});

The end result I get with this code is:

enter image description here

-edit- Would the proper way to do this be to create my nodes first using .forEach, then passing the created nodes to the render function's return? (I'm looking at the React Tutorial at React Docs. Would my original solution be possible, or is the only way to pre-create the nodes before returning them?

1 Answer 1

4

You need to use map instead of forEach. forEach returns nothing, so the result is:

<div class="subTraitContainer">
  <div></div>
<div>

map returns an array. It maps each element in the given array to something new. For example, you could map an array of Users to their usernames. If you use map instead of forEach, you will get an array of <div>s, which should do what you expected.

Sign up to request clarification or add additional context in comments.

Comments

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.