Show available variants
This guide shows you how to render a product form that includes a list of available product variants.
Requirements
Anchor link to section titled "Requirements"- You've completed the quickstart guide.
- You've set up a cart handler.
Selecting Variants with Links
Anchor link to section titled "Selecting Variants with Links"Many product pages include a form where options are submitted to the server when the user adds to the cart. The most basic product form enables customers to select from available variants. For example, variants might include product size and color.
In Hydrogen we recommend using a Link
to select each variant. This automatically updates the URL when customers select a variant, which has the following benefits:
- Search engines can easily index each separate variant.
- Users can share and bookmark each separate variant.
- Variants can be prefetched on hover, which decreases the perceived load time.
Query the Storefront API for Product Options
Anchor link to section titled "Query the Storefront API for Product Options"First, your product query needs to include product options. Do this by adding options
with the name
and optionValues
properties:
VariantSelector component
Anchor link to section titled "VariantSelector component"Now that you've queried product options, you can use the VariantSelector
component to render links for all product options:
Calculating the selected product
Anchor link to section titled "Calculating the selected product"To calculate the selected product options based on URL parameters, update your GraphQL query to use the variantBySelectedOptions
and use getSelectedProductOptions
:
Product Variants by Availability
Anchor link to section titled "Product Variants by Availability"Sometimes you might want to render the variants differently based on product availability. You can do this by adding product variants to your Storefront API query.
Add variants
to the product query and include the availableForSale
property. Because variants
is a list, you have to decide how many items to query. You can include all items, but for efficiency we recommend doing this if you only have a handful to query. For example, querying all if you have one hundred variants can have a negative impact on performance.
Add to cart
Anchor link to section titled "Add to cart"Use the CartForm
component to add the selectedVariant to the cart. You can also disable the add to cart button if the selected variant is invalid or unavailable:
Automatically select a default variant
Anchor link to section titled "Automatically select a default variant"You may want to automatically have a variant selected when the page first loads. We recommend selecting a default variant by redirecting to a variant from the loader:
- Learn how to update metafields.