1

I want my RenderDOM to render one component for each object found in an array. I'm building the render with JSX, and my code is as follows:

ReactDOM.render((
            <div className="container container-collapsed">
                <Actions Units={aUnits} />
                <div className="units-wrapper">
                    {
                        aUnits.forEach(u=> {
                            return <Unit unit={u} />
                        })
                    }
                </div>
            </div>
        ), document.getElementById("root"));

I expeted the output to be like this:

<div class="container container-collapsed">
    <div class="actions-panel_true"></div>
    <div class="units-wrapper">
        <div class="unit1"></div>
        <div class="unit2"></div>
        <div class="unit3"></div>
    </div>
</div>

And instead I'm getting:

<div class="container container-collapsed">
    <div class="actions-panel_true"></div>
    <div class="units-wrapper"><div>
</div>

I know that my foreach is working, I debbuged it. But it is not building one JSX per units as I expcted. How to I make this foreach loop return one component for each object in my array, back to the JSX i'm trying to render?

2 Answers 2

4

You need .map instead of .forEach to return an array so that React can render it effectively.

Also returning from the callback inside .forEach has no use since .forEach doesn't return an array. It returns undefined.

.forEach is useful when you want to change the contents of existing array without returning a new one. In React, JSX requires an array as a result of .map operation.

Also more valid points covered by @zhulien

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

Comments

3

This should do:

ReactDOM.render((
   <div className="container container-collapsed">
      <Actions Units={aUnits} />
      <div className="units-wrapper">
         {aUnits.map(unit => {
            return (
               <Unit key={u.key} unit={u} />
            );
         })}
       </div>
   </div>
), document.getElementById("root"));

A couple notes:

<Unit={u} />

is not a valid syntax. You are suppose to assign u to a property of the Unit component, not the component itself. Also, when rendering array of items, you should supply a key property to each item as to help React differentiate between them. You'll find more information about why this is important In the React docs.

1 Comment

Thank you! <Unit={u}/> was a typo in my question. I'll update it. On the actual code I'm doing <Unit unit={u}/> as you pointed out.

Your Answer

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