1

I have the following code in my React component render method

render: function() {
    return (
       <div>
           <div>div1</div>
           <div>div2</div>
           {this.getOtherDivs()}
       </div>
    );
},

getOtherDivs: function() {
   return ([
       <div>div3</div>,
       <div>div4</div>       
   ]);
},

However, these two divs div3 and div4 are nested into single array instead of being separate.

When I do children.length for the top most div, I am getting 3 instead of 4.

I don't want to wrap the last two divs in an enclosing div.

2
  • 2
    I did a quick test using React v16.2.0 and both the pure HTML inspect and the React tab (from React DevTools) in Chrome show 4 divs inside another div. Can you provide details about how you are calling children.length? Where exactly does that come from? Also, what version of React are you using? Commented Jan 29, 2018 at 18:35
  • Your code should work Commented Jan 29, 2018 at 18:39

3 Answers 3

3

Try using <React.Fragment />.

getOtherDivs: function() {
   return (
     <>
       <div>div3</div>
       <div>div4</div>
     </>       
   );
},
Sign up to request clarification or add additional context in comments.

Comments

0

you use map to loop on the array and return the divs directly to main div

render: function() {
    return (
       <div>
           <div>div1</div>
           <div>div2</div>
           {this.getOtherDivs().map(item => item)}
       </div>
    );
},

2 Comments

Why the map ?
this.getOtherDivs() already returns an array of React elements. .map(item => item) literally does nothing.
0

You can do it using map

Declare an array of items:

const items = [div3, div4];

Now your render method should look like:

render() {
    return (
       <div>
           <div>div1</div>
           <div>div2</div>
           {this.items.map(item => <div>{item}</div>)}
       </div>
    );
}

If you have an array of objects, then you can do it like this:

Declare an array of arrays:

const items = [[div3, div4],[div5, div6],[div7, div8]];

Then in your render method:

render() {
    return (
       <div>
           <div>div1</div>
           <div>div2</div>
           {this.items.map(item => 
               <div>
                   <div>item[0]</div>
                   <div>item[1]</div>
               </div>
           )}
       </div>
    );
}

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.