Adding Products to Our Cart with Snipcart

Learn how to define products with Snipcart.

Previously, we learned that Snipcart is a technology that makes it easy to implement cart systems and cart management within our web application. Snipcart works by first creating an account and installing Snipcart in our project with our API KEY, either the LIVE or TEST key. This gives us access to some Snipcart classes and attributes, which we can add to our HTML element to reflect information from our Snipcart account or perform carting operations.

Add products to cart

In our project, we have a "Add to Cart" button; all we have to do is add the snipcart-add-item class to the button. This instructs Snipcart to respond to the element's click event. Then we pass some product values via specific attributes, such as the product price, image, name, and description.

There are five significant attributes:

  • Name: This represents the product name and is defined with the data-item-name attribute, whose value is a string. It is a required field.

  • ID: This represents the product's unique ID and is defined with the data-item-id attribute, whose value is a string. It is also a required field.

  • Price: This represents the product's price, in which we must use a dot (.) as a decimal separator. It is defined with the data-item-price attribute, whose value is a number. It is also a required field.

  • Description: This represents the product description and is defined with the data-item-description attribute, whose value is a string. It is not a required field.

  • Image: This represents the product image URL and is defined with the data-item-image as an attribute, whose value is a string. It is not a required field. Avoid linking to large images–instead, use an optimized version.

Let's now add this data to our shop page and then add it to other pages.

Product definition for the shop page

On the shop page, we have the "Add to cart" button for all our products that we looped through, meaning we would only have to implement this for the button once and add all the data dynamically from our Hygraph content repository.

Note: The API_URL added to the code is from our Hygraph CMS, while the SNIPCART_PUBLIC_API is from the Snipcart account you created.

Get hands-on with 1200+ tech skills courses.