3.9 KiB
3.9 KiB
The UnitPrice
component renders a string with a UnitPrice as the
Storefront API's MoneyV2
object with a reference unit from
the Storefront API's UnitPriceMeasurement
object.
If children
is a function, then it will provide render props for the children
corresponding to the object
returned by the useMoney
hook and the UnitPriceMeasurement
object.
Example code
import {UnitPrice} from '@shopify/hydrogen';
import gql from 'graphql-tag';
const QUERY = gql`
productByHandle(handle: "my-product") {
variants(first: 1) {
edges {
node {
unitPriceMeasurement {
measuredType
quantityUnit
quantityValue
referenceUnit
referenceValue
}
unitPrice {
amount
currencyCode
}
}
}
}
}
`;
export default function Product() {
const {data} = useShopQuery({query: QUERY});
const selectedVariant = data.product.variants.edges[0].node;
return (
<UnitPrice
unitPrice={selectedVariant.unitPrice}
unitPriceMeasurement={selectedVariant.unitPriceMeasurement}
/>
);
}
export default function ProductWithCustomUnitPrice() {
const {data} = useShopQuery({query: QUERY});
const selectedVariant = data.product.variants.edges[0].node;
return (
<UnitPrice
unitPrice={selectedVariant.unitPrice}
unitPriceMeasurement={selectedVariant.unitPriceMeasurement}
>
{({amount, currencyCode, currencyNarrowSymbol, referenceUnit}) => {
return (
<>
<span>{`${currencyNarrowSymbol}${amount}/${referenceUnit}`}</span>
<span>{currencyCode}</span>
</>
);
}}
</UnitPrice>
);
}
Props
Name | Type | Description |
---|---|---|
unitPrice | MoneyV2 |
A MoneyV2 object. |
unitPriceMeasurement | UnitPriceMeasurement |
A UnitPriceMeasurement object. |
children? | ReactNode |
A function that takes an object returned by the UnitPrice component and returns a ReactNode . |
as? | ReactNode |
A ReactNode |
Component type
The UnitPrice
component is a client component, which means that it renders on the client. For more information about component types, refer to React Server Components.
GraphQL fragment
The following fragment is available as a string for your GraphQL query using UnitPriceFragment
or UnitPrice.Fragment
. Using this fragment ensures that you have all the data necessary for rendering the UnitPrice
component.
fragment UnitPriceFragment on ProductVariant {
unitPriceMeasurement {
measuredType
quantityUnit
quantityValue
referenceUnit
referenceValue
}
unitPrice {
...MoneyFragment
}
}