user7362545
user7362545

Reputation:

ReactDOM dynamically rendering components from array

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?

Upvotes: 1

Views: 231

Answers (2)

Lakshya Thakur
Lakshya Thakur

Reputation: 8308

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

Upvotes: 4

zhulien
zhulien

Reputation: 5695

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.

Upvotes: 3

Related Questions