Im trying to change style of only one element in map onClick, but it changes every element instead of one.
const maping = () => {
return orders.map((item, index) =>
<div className={styles.orders} key={index} onClick={() => {setSelectedAns("4px 3px 8px 0px rgba(1, 156, 48 , 0.3)")}} style={{boxShadow: selectedAns}}>
<div className={styles.orderIDContainer}>
<p className={styles.orderID}>{item.id}</p>
</div>
<div className={styles.description}>
{item.description.map((food, index2) => { return (<p key={index2}> <font>{food.quantity}x</font> {food.foodItem.name} </p>) })}
</div>
</div>);
};
Any ideas how to do it?
You can use a ternary operator which chooses between the two values you want based on a state (named myStyle
) of each particular iteration using the index i
.
Note that this is assuming you want the style to change back and forth everytime you click.
Also note that it will only work if you aren't planning on dynamically reordering the items you are mapping through, otherwise you shouldn't use the index
as the key
but rather you should use an id
.
const [myStyle, setMyStyle] = useState({});
const messages = [
{ content: "hi" },
{ content: "bonjour" },
{ content: "hola" }
];
const handleClick = (id) => {
setMyStyle(prevState => ({
...myStyle,
[id]: !prevState[id]
}))
}
return (
<div>
{messages.map((message, i) => (
<div
key={i}
style={{
boxShadow: myStyle[`${i}`]
? "4px 3px 8px 0px rgba(1, 156, 48, 0.3)"
: "initial"
}}
onClick={() => handleClick(i)}
>
{message.content}
</div>
))}
</div>
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With