top of page

For Loops in React Render() - No You Didn't!

Let's say you want to programmatically create a table in React. Something like:

Looks like we could use for loops to generate the desired code. In this case we'd need a nested loop, one of the three rows and one for each of their five children.

Million Dollar Question:

What happens when you stick the for loops in the render() function?

Error!

=> "Syntax error: Unexpected token"

Apparently React does not like for loops in its render() method! How do we solve this?

What we need to do is create the table in a separate function outside render(), but still inside the class. Then we can call the creating function inside render to get the result.

But. There are a few pitfalls to look out for. This will not work:

Why? You cannot create children for a parent that does not exist yet.

What we need to do in the first step is to create all the children.

And then in the second step we can create the parent (our table row <tr>) and assign the children to it.

Our code will look like this:

And an extra tipp for those who are using Semantic UI: <Table> has property of "children". So you'd create your row like this in line 16:

table.push(<Table.Row children={children} />)

You Might Also Like:
bottom of page