Reputation: 123
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?
Upvotes: 0
Views: 33
Reputation: 1568
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>;
Upvotes: 1
Reputation: 2056
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>
);
}
Upvotes: 1