hydrogen/packages/hydrogen/src/components/Money/README.md
2021-11-09 18:20:09 -08:00

2.8 KiB

The Money component renders a string of the Storefront API's MoneyV2 object according to the locale in the shopify.config.js file. If children is a function, then it will provide render props for the children corresponding to the object returned by the useMoney hook.

Example code

import {Money} from '@shopify/hydrogen';
import gql from 'graphql-tag';

const QUERY = gql`
  productByHandle(handle: "my-product") {
    variants(first: 1) {
      edges {
        node {
          priceV2 {
            amount
            currencyCode
          }
        }
      }
    }
  }
`;

export default function Product() {
  const {data} = useShopQuery({query: QUERY});

  return <Money money={data.product.variants.edges[0].node.priceV2} />;
}

export default function ProductWithCustomMoney() {
  const {data} = useShopQuery({query: QUERY});

  return (
    <Money money={data.product.variants.edges[0].node.priceV2}>
      {({amount, currencyCode, currencyNarrowSymbol}) => {
        return (
          <>
            <span>{`${currencyNarrowSymbol}${amount}`}</span>
            <span>{currencyCode}</span>
          </>
        );
      }}
    </Money>
  );
}

Props

Name Type Description
as? ElementType A ReactNode element.
money MoneyV2 A MoneyV2 object.
children? ReactNode A function that takes an object return by the useMoney hook and returns a ReactNode.

Component type

The Money 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 MoneyFragment or Money.Fragment. Using this fragment ensures that you have all the data necessary for rendering the Money component.

fragment MoneyFragment on MoneyV2 {
  currencyCode
  amount
}