Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change style of one element in map using react?

Tags:

reactjs

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?

like image 697
M3zuss Avatar asked Sep 16 '25 08:09

M3zuss


1 Answers

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

Edit hungry-platform-rtsedg

like image 64
Monstar Avatar answered Sep 17 '25 23:09

Monstar