useState
import { useState } from "react"; export default function App() { const [products, setProducts] = useState([ { name: "product 1", price: 100.0 }, { name: "product 2", price: 200.0 }, { name: "product 2", price: 200.0 }, ]); const addProduct = () => { setProducts((prevState) => [ ...prevState, { name: "product " + (prevState.length + 1), price: prevState.length * 100 + 100, }, ]); }; return ( <> <h1>Products</h1> <ul> {products.map((p, i) => ( <li key={i}> {p.name} - {p.price} </li> ))} </ul> <button onClick={addProduct}>Add Product</button> </> ); }
655 views