Randex Randex - 1 month ago 4
Javascript Question

Can I count elements in JSX before rendering?

I have a class that has a table in it. Problem is, amount of columns in it may vary. And when no data is loaded to the table, I need to display a message here something like "no data", using

<td colSpan="#"></td>
. I need to determine the number of columns in the table for
colSpan
, in other words, I want to count the number of
th
elements in the header of the table. Is it possible in
render
method or maybe there's better way to do it?

I think I could render the table without that "no data" message, and then insert it using jQuery in
componentDidUpdate
, but something tells me it's a bad idea...

Answer

You can use the React Children utility to determine if there are any elements inside (considering you had a parent Table element that would wrap TableRow or TableHeader elements). I think that would be the most appropriate approach here.

That way you can dynamically render content and also be able to tell how many elements you need to render.

What you might be looking for more exactly would be the React.Children.count.