I have this React code defining optionTemplate
which is intended to be passed as a prop of a React component.
const optionTemplate = (option) => {
return (
<div
className="flex align-items-center gap-2"
style={{ fontSize: "1.5rem" }}
>
{option[props.optionGroupChildren[0]] && (
<i
className={option.icon.icon}
style={{ color: option.icon.color, fontSize: option.icon.size }}
/>
)}
{option[props.optionGroupChildren[1]] && (
<i
className={option.icon.icon}
style={{ color: option.icon.color, fontSize: option.icon.size }}
/>
)}
{option[props.optionLabel] && (
<i
className={option.icon.icon}
style={{ color: option.icon.color, fontSize: option.icon.size }}
/>
)}
<span style={{ fontSize: "1.5rem" }}>{option[props.optionLabel]}</span>
<span style={{ fontSize: "1.5rem" }}>{option[props.optionGroupLabel]}</span>
</div>
);
};
Observe this piece of code:
{option[props.optionGroupChildren[0]] && (
<i
className={option.icon.icon}
style={{ color: option.icon.color, fontSize: option.icon.size }}
/>
)}
{option[props.optionGroupChildren[1]] && (
<i
className={option.icon.icon}
style={{ color: option.icon.color, fontSize: option.icon.size }}
/>
)}
The number of elements of props.optionGroupChildren
can be arbitrary so I would like to generalize:
{option[props.optionGroupChildren[0]] && (
<i
className={option.icon.icon}
style={{ color: option.icon.color, fontSize: option.icon.size }}
/>
)}
{option[props.optionGroupChildren[1]] && (
<i
className={option.icon.icon}
style={{ color: option.icon.color, fontSize: option.icon.size }}
/>
)}
.......
{option[props.optionGroupChildren[n]] && (
<i
className={option.icon.icon}
style={{ color: option.icon.color, fontSize: option.icon.size }}
/>
)}
I googled "jsx for loop" but I have not been convinced that what I found was appropriate for my situation.
2
Answers
You’d use
map
for that (more in the React documentation), something like this although I didn’t see where you were using the value ofoption[props.optionGroupChildren.map[n]]
(unless it’s really only used for the&&
guard):Note the
key
, which is essential on arrays so React can keep track of elements as they move around. Don’t just use the index of the element as the key, it’s not sound unless the array never changes. (More here.)As stated by @cmgchess you could use maps in order to render your list.
As shown in the documentation.
The map function could be seen as a for loop, like in those simple examples:
Both methods will return the same output, since internally the map function iterates throught the itens in a list and runs them against the callback.
Therefore you could use map as something like: