React JSX inner loop
P粉966979765
P粉966979765 2023-08-23 14:08:12
0
2
534
<p>I'm trying to do something like the following in React JSX (where the ObjectRow is a separate component): </p> <pre class="brush:php;toolbar:false;"><tbody> for (var i=0; i < numrows; i ) { <ObjectRow/> } </tbody></pre> <p>I realize and understand why this is not valid JSX, since JSX maps to function calls. However, coming from the template world and new to JSX, I'm not sure how to achieve the above goal (adding components multiple times). </p>
P粉966979765
P粉966979765

reply all(2)
P粉609866533

I'm not sure if this is appropriate for your case, but usually map is a good answer.

If this is your code using a for loop:

<tbody>
    for (var i=0; i < objects.length; i++) {
        <ObjectRow obj={objects[i]} key={i}>
    }
</tbody>

You can use map to write 一> like this:

<tbody>
    {objects.map(function(object, i){
        return <ObjectRow obj={object} key={i} />;
    })}
</tbody>

ES6 syntax:

<tbody>
    {objects.map((object, i) => <ObjectRow obj={object} key={i} />)}
</tbody>
P粉937769356

Think of it as if you were just calling a JavaScript function. You cannot use a for loop to pass arguments to a function call:

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

See how the function tbody is passed as a parameter to the for loop - causing a syntax error.

But you can create an array and pass it as a parameter:

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

You basically use the same structure when using JSX:

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

By the way, my JavaScript example converts almost exactly the same thing as the JSX example. Try using Babel REPL to get a feel for how JSX works.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template