Search code examples
reactjstoggle

Toggle click on a mapped data React JS


Here is my main component in which I render a component based on the data I receive from API:

  <div className="PlayersContainer">
          {players.map((player) => {
            return (
              <PlayerPhoto
                key={player._id}
                {...player}
                selected={selected}
                something={(e) => {
                  setSelected(!selected);
                 }}
              />
            );
          })}
        </div>

and here is inside my component: export default function PlayerPhoto({ name, img, something, selected }) {

  return (
    <article
      className={selected ? styles.Fade : styles.PlayerBox}
      onClick={something}
    >
      <img src={img} alt={name} className={styles.PlayerPhoto} />
      <p className={styles.PlayerName}>{name}</p>
    </article>
  );
}

What I'm trying to do is that when the user clicks on a player it shoud take the fade class and become fade, and when the user clicked again it should returns to its normal class.

the problem is when the user clicks on a player all players get the fade class and become selected. How can I get their id and add the fade class to that specific player id?


Solution

  • Why are you not move this logic to PlayerPhoto?

    export default function PlayerPhoto({ name, img }) {
      const [selected, setSelected] = React.useState(false);
      return (
        <article
          className={selected ? styles.Fade : styles.PlayerBox}
          onClick={()=>setSelected((prevValue)=>!prevValue}
        >
          <img src={img} alt={name} className={styles.PlayerPhoto} />
          <p className={styles.PlayerName}>{name}</p>
        </article>
      );
    }