HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptreactCritical

Loop inside React JSX

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
loopreactinsidejsx

Problem

I'm trying to do something like the following in React JSX (where ObjectRow is a separate component):


    for (var i=0; i 
    } 


I realize and understand why this isn't valid JSX, since JSX maps to function calls. However, coming from template land and being new to JSX, I am unsure how I would achieve the above (adding a component multiple times).

Solution

Think of it like you're just calling JavaScript functions. You can't use a for loop where the arguments to a function call would go:

return tbody(
    for (let i = 0; i < numrows; i++) {
        ObjectRow()
    } 
)


See how the function tbody is being passed a for loop as an argument – leading to a syntax error.

But you can make an array, and then pass that in as an argument:

const rows = [];
for (let i = 0; i < numrows; i++) {
    rows.push(ObjectRow());
}
return tbody(rows);


You can basically use the same structure when working with JSX:

const rows = [];
for (let i = 0; i );
}
return {rows};


Incidentally, my JavaScript example is almost exactly what that example of JSX transforms into. Play around with Babel REPL to get a feel for how JSX works.

Code Snippets

return tbody(
    for (let i = 0; i < numrows; i++) {
        ObjectRow()
    } 
)
const rows = [];
for (let i = 0; i < numrows; i++) {
    rows.push(ObjectRow());
}
return tbody(rows);
const rows = [];
for (let i = 0; i < numrows; i++) {
    // note: we are adding a key prop here to allow react to uniquely identify each
    // element in this array. see: https://reactjs.org/docs/lists-and-keys.html
    rows.push(<ObjectRow key={i} />);
}
return <tbody>{rows}</tbody>;

Context

Stack Overflow Q#22876978, score: 1828

Revisions (0)

No revisions yet.