Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use For loop inside JSX [duplicate]

Can you use a for loop in JSX like this?
Or rather, what is the propper way to write a for like this?

var graph = 
        <div className={"chartContent"}>

        .
        .
        .

            <div className="panel">
                {DataRows.forEach(function(entry) &&
                    <div className="col-sm-2 graphPanel graphPanelExtra">
                        <div className="panel panel-primary">
                            <div>entry</div>
                        </div>
                    </div>
                )}

            </div>
        </div>;
like image 376
morne Avatar asked Sep 14 '17 10:09

morne


1 Answers

Use a map so you're actually returning the elements. A foreach doesn't return anything. Your use of && was also invalid.

var graph = 
        <div className="chartContent">
            <div className="panel">
                {DataRows.map(entry =>
                    <div key={entry.id} className="col-sm-2 graphPanel graphPanelExtra">
                        <div className="panel panel-primary">
                            <div style={{ textAlign: 'center' }}>entry</div>
                        </div>
                    </div>
                )}
            </div>
        </div>;

Note that I added a key property - for react to optimise rendering of an array of elements each item should have a unique key (that isn't just the numeric index).

like image 95
Dominic Avatar answered Sep 24 '22 17:09

Dominic