klixo
klixo

Reputation: 452

onClick in Map func,only execute for one element

Is there any method for map function to only execute Dropdown menu for one cart.For now if i click on one Menu icon , every dropdown appears for every Card in map.

 const [isOpen, setIsOpen] = useState(false);
  {albums.map((album, i) => (
        <Card width="23rem" height="16rem" bckImg={album.bckImgUrl} key={i}>
          <AlbumtTitle color={album.color}>{album.name}</AlbumtTitle>
          <LinkButton background={album.color} to={`/albums/${album._id}`}>
            See more
          </LinkButton>
          <KebabMenu onClick={() => setIsOpen(!isOpen)} open={isOpen}>
            {isOpen ? (
              <Dropdown
                ref={ref}
                style={{
                  width: "50px",
                  height: "50px",
                }}
              >
                <li>
                  <Link to={`editAlbum/${album._id}`}>Edit</Link>
                </li>
                <hr />
                <li>Delete</li>
              </Dropdown>
            ) : (
              <Dots />
            )}
          </KebabMenu>
        </Card>
      ))}

Upvotes: 2

Views: 704

Answers (2)

IvanD
IvanD

Reputation: 2923

Instead of

 {albums.map((album, i) => (...your code...))}

you need to check whether you have at least one item in albums, and if yes, process it:

{if (albums.length > 0) {
   return albums.slice(0,1).map((album, i) => (...your code...))
 } else {
   return null // or any other actions you want to take in case there are no albums
 }
}

To clarify, we check the length of the albums, if it is not empty. If it is, we take only the first element and process it.

Upvotes: 0

Nick
Nick

Reputation: 16576

Your isOpen state can be an object that tracks the open state per item in the album:

const [isOpen, setIsOpen] = useState({});

{albums.map((album, i) => (
    <Card width="23rem" height="16rem" bckImg={album.bckImgUrl} key={i}>
      <AlbumtTitle color={album.color}>{album.name}</AlbumtTitle>
      <LinkButton background={album.color} to={`/albums/${album._id}`}>
        See more
      </LinkButton>
      <KebabMenu
        onClick={() =>
          setIsOpen({ ...isOpen, [album._id]: !isOpen[album._id] })
        }
        open={!!isOpen[album._id]}
      >
        {isOpen[album._id] ? (
          <Dropdown
            ref={ref}
            style={{
              width: "50px",
              height: "50px",
            }}
          >
            <li>
              <Link to={`editAlbum/${album._id}`}>Edit</Link>
            </li>
            <hr />
            <li>Delete</li>
          </Dropdown>
        ) : (
          <Dots />
        )}
      </KebabMenu>
    </Card>
  ))}

Upvotes: 4

Related Questions