9

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>;
0

3 Answers 3

8

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).

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

4 Comments

Hi Dominic. If its (entry) a Key Value pair. How do you seperate the values? Please.
entry is an object? In that case you could do Object.keys(entry).map(...
Yeah, sorry. just saw that. thanks
map is the correct way to go as it returns a modified array.
1

The forEach does not return anything. You wont see any results out of it. Instead you could use .map e.g.

 {
     DataRows.map(function (entry) {
             return <div className="col-sm-2 graphPanel graphPanelExtra">
                        <div className="panel panel-primary">
                            <div style={{textAlign: 'center'}}>entry</div>
                        </div> < /div>
                })
}

Comments

1

Rather than using a forEach loop you can use Array.prototype.map()

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

    .
    .
    .

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

        </div>
    </div>;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.