Home > database >  how to get an array into another array with a button in react
how to get an array into another array with a button in react

Time:01-21

so i have an array

const products = [{
    name: "14K bracelet",
    id: "1",
    description: "Beautfull 14K gold Bracelet",
    price: 100.00,
    
  }]

im trying to make it so whenever someone presses this button

<Button className="btn btn-primary btn-rings" href="#" onClick={() => cart}>Add To Cart</Button>

, it gets added to this array/state


const [cart, setCart] = useState([])

does anyone know how i would do this,

also how would i get whats showing in the carts, to show up in here

{products.map((products) => <h1 key={products.id} className="price>{"$"   products.price}</h1>)}

CodePudding user response:

Whenever you click a button you need to set the state using useState hooks which you have defined above. Hope this solves your problem

<Button className="btn btn-primary btn-rings" href="#" onClick={() => setCart(products )}>Add To Cart</Button>

CodePudding user response:

I assume you're using .map() to render the products. You just have to add the product to your list of items.

{
  { products.map(product => (
    <Button key={product.id} onClick={() => setCart(cart => [product, ...cart])}>
      Add To Cart
    </Button>
  ))}
}

You should probably get yourself more familiar with state hooks also: https://reactjs.org/docs/hooks-state.html

  •  Tags:  
  • Related