javascript – Loop inside React JSX
There are multiple ways to go about doing this. JSX eventually gets compiled to JavaScript, so as long as you’re writing valid JavaScript, you’ll be good.
My answer aims to consolidate all the wonderful ways already presented here:
If you do not have an array of object, simply the number of rows:
Within the return
block, creating an Array
and using Array.prototype.map
:
render() {
return (
<tbody>
{Array(numrows).fill(null).map((value, index) => (
<ObjectRow key={index}>
))}
</tbody>
);
}
Outside the return
block, simply use a normal JavaScript for loop:
render() {
let rows = [];
for (let i = 0; i < numrows; i++) {
rows.push(<ObjectRow key={i}/>);
}
return (
<tbody>{rows}</tbody>
);
}
Immediately invoked function expression:
render() {
return (
<tbody>
{(() => {
let rows = [];
for (let i = 0; i < numrows; i++) {
rows.push(<ObjectRow key={i}/>);
}
return rows;
})()}
</tbody>
);
}
If you have an array of objects
Within the return
block, .map()
each object to a <ObjectRow>
component:
render() {
return (
<tbody>
{objectRows.map((row, index) => (
<ObjectRow key={index} data={row} />
))}
</tbody>
);
}
Outside the return
block, simply use a normal JavaScript for loop:
render() {
let rows = [];
for (let i = 0; i < objectRows.length; i++) {
rows.push(<ObjectRow key={i} data={objectRows[i]} />);
}
return (
<tbody>{rows}</tbody>
);
}
Immediately invoked function expression:
render() {
return (
<tbody>
{(() => {
const rows = [];
for (let i = 0; i < objectRows.length; i++) {
rows.push(<ObjectRow key={i} data={objectRows[i]} />);
}
return rows;
})()}
</tbody>
);
}
Read more here: Source link