0

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?

3
  • why don't you store the id of the player on click and in the selected option check if current player id and the selected one match if so then it fades other it won't Commented Feb 14, 2022 at 10:32
  • I want but I dont know how since I am a totally newbie Commented Feb 14, 2022 at 10:42
  • have a look at stackoverflow.com/a/71110558/17497509 @Shan answer that's what I was saying Commented Feb 14, 2022 at 10:51

2 Answers 2

1

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>
  );
}

Sign up to request clarification or add additional context in comments.

Comments

1

Create a state to maintain the selected id and then compare the selectedId and player id for the selected prop boolean value. if the id matches , it will change the className.

const [selectedId, setSelectedId] = useState(null);

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.