Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React JS mapped array – render a single item

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:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
)}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading