Liiaam93
Liiaam93

Reputation: 285

React / NextJS - onClick targets all mapped items - how do i target just one?

Couldn't figure out a better way to word the problem i have, sorry if this gets asked often.

Code is like this:

  const [isFlipped, setFlipped] = useState(false);

  const flip = () => {
    if (!isFlipped) {
      setFlipped(true);
    } else {
      setFlipped(false);
    }
  };
return(
data.map((product) => (
  <div 
    onClick={()=> flip()}
    animate={isFlipped && { rotateY: 180 }}
>
    <p>{product.name}</p>
    <p>{product.info}</p>
  </div>
 ));
)

i want the flip() function to work only on the div that gets clicked, however currently it affects every mapped div.

Upvotes: 0

Views: 1073

Answers (1)

Casey Knight
Casey Knight

Reputation: 81

Edit (After seeing the flip function): You should make this a seperate component so each child has it's own isFlipped State. And then map and create the components with the product as a prop.

Add a key to the div in the map to add uniqueness.

data.map((product, key) => (
  <div key={key} onClick={()=> flip()}>
    <p>{product.name}</p>
    <p>{product.info}</p>
  </div>
 ));

Upvotes: 2

Related Questions