简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM