Example: Show Product Variant
Format and display a variant's price.
On this page
In this guide, you'll learn how to display a product variant's price with a full React example.
Tip: This guide doesn't take into account sale or tax prices. Refer to the following guides to learn how to show them:
Price Formatting
To format a price, use JavaScript's NumberFormat utility. You pass it the amount and the currency code (which you retrieve from the selected region):
Tip: Refer to the Store Selected Region guide to learn how to store and retrieve the selected region's currency code.
ts
You'll use this function to format prices in your storefront, including the selected variant's price.
Display Selected Variant Price
Once the customer selects a variant (as explained in the Select Product Variants guide), use its calculated_price.calculated_amount property to display its price:
ts
The price variable holds the formatted price of the selected variant with the currency of the selected region.
Tip: Learn about the calculated_price field in the Retrieve Product Variant's Prices section.
Full React Example
The following React-based storefront example retrieves the product's price based on the selected variant:
Tip: - This example uses the useRegion hook defined in the Region React Context guide to retrieve the selected region's currency code.
- Learn how to install and configure the JS SDK in the Getting started guide.
tsx
In the example above, you:
- Use the
useRegionhook defined in the previous Region React Context guide to retrieve the selected region's currency code. This is necessary to format the variant's price. - Pass the pricing query parameters to the request retrieving the product. This retrieves for every variant a new
calculated_pricefield holding details about the variant's price.- You can pass other pricing query parameters for more accurate pricing. Refer to the Retrieve Product Variant's Prices guide for more information.
- Choose the variant to show its price:
- If there's a selected variant, choose it.
- If there isn't a selected variant, retrieve and choose the variant with the cheapest price.
- Format the price based on the chosen variant in the previous step. The variant's
calculated_price.calculated_amountfield is used. - Display the formatted price to the customer. If there isn't a select variant, show a
Fromlabel to indicate that the price shown is the cheapest.