I have a React front end, which renders an array of rows based on objects from an API. I am mapping the object array, which works as intended. If the condition is met, an icon button is displayed. If the condition of the child elements below (sector.properties.length === 0) is true multiple times, multiple buttons will be rendered in the row. I am trying to only display a single button if the condition is true, but am struggling to figure it out.
{data.sectors.map((sector, index) => (
<SingleLineCell
key={`${data.productName}Product${index}`}
>
{sector.properties.length === 0 && (
<button
type="button"
onClick={() =>
showModal('DeleteData', {
form: data,
onConfirmDelete: () => {
onConfirmDelete(data);
}
})
}
>
<IconDelete responsive />
<span className="sr-only">Delete {data.productName} Product</span>
</button>
)}
</SingleLineCell>
))}
So this is what is currently rendered. I want to only render the first button, even when the condition is true multiple times:
CodePudding user response:
If the map
is just used to display this button then instead of map
use first some
to check if the data satisfies the condition and then just print the button.
{data.sectors.some((sector) => sector.properties.length === 0) && (
<SingleLineCell
key={`${data.productName}Product`}
>
<button
type="button"
onClick={() =>
showModal('DeleteData', {
form: data,
onConfirmDelete: () => {
onConfirmDelete(data);
}
})
}
>
<IconDelete responsive />
<span className="sr-only">Delete {data.productName} Product</span>
</button>
</SingleLineCell>
)}