Loop inside React JSX

Loop inside React JSX

Published at - Aug 13, 2021

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

return tbody(
    for (var i = 0; i < numrows; i++) {

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:

var rows = [];
for (var i = 0; i < numrows; i++) {
return tbody(rows);

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

var rows = [];
for (var 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>;

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.

About author

Harendra Kanojiya

Hello, I am Harendra Kumar Kanojiya - Owner of this website and a Fullstack web developer. I have expertise in full-stack web development using Angular, PHP, Node JS, Python, Laravel, Codeigniter and, Other web technologies. I also love to write blogs on the latest web technology to keep me and others updated. Thank you for reading the articles.

Related Posts -

React with WordPress API
React with WordPress API ...

Hello, Today I am going to explore how you can use WordPress API to run a ...

Why use Redux over Facebook Flux?
Why use Redux over Facebook ...

https://stackoverflow.com/a/32920459/6720451 Redux is not that differ...

What are the features of React JS?
What are the features of Re ...

React Js is used to develop single-page web application and have many feat...

React Component to Smooth Scroll to the Top
React Component to Smooth S ...

We often required a scroll to the top of our page so I have planned to cre...

Follow Us

Follow us on facebook Click Here

Facebook QR
Scan from mobile
Join our telegram channel Click Here
Telegram QR
Scan from mobile