# Elements React Components The `@shipengine/elements` package provides the full suite of ShipEngine Elements as React components. ## Quick Start ```bash npm install @shipengine/elements ``` ### Install Peer Dependencies: ```bash npm install react@17.x react-dom@17.x i18next@22.x react-i18next@11.x @emotion/react@11.x ``` ### Elements Provider Render an Elements provider at the root of your React app so that it is available everywhere you need it. Available to all descendants of the `ElementsProvider`: 1. A batteries-included client for accessing ShipeEngine API endpoints with a shared cache and lifecycle management via react hooks. 2. A theme, which can be re-defined at instantiation via the `themeConfig` prop. 3. Configurable features, available via the `features` prop. ## Initialize Elements ```jsx import { PurchaseLabel, ElementsProvider } from '@shipengine/elements'; import { themeConfig } from '../themeConfig'; const tokenPath = '/path/to/token/endpoint'; const Foo = ({ shipments }) => { const [selectedShipment, setSelectedShipment] = useState(); const getToken = useCallback(() => { return fetch(tokenPath).then((res) => res.text()); }, []); return ( {selectedShipment && ( )} ); }; ``` > **WARNING:** The **emotionCacheShadowRootContainer** prop is *deprecated* but still supported for backward compatibility. The components now handle shadow DOM creation and rendering automatically. We recommend removing this prop from your code. See the **container** prop for more details. | Args/Props | Description | | --- | --- | | `getToken` | *function*, **required** A callback function that fetches and refreshes the tokens used by Elements. Check out the [Elements Getting Started guide](/apis/shipengine/docs/elements/getting-started) for more detailed information about generating Elements tokens. | | `baseURL` | *string*, **optional** A fully qualified domain name used as the base URL to route all API calls from the Elements. This is defaulted to `https://elements.shipengine.com` | | `container` | *HTMLElement*, **optional** A DOM element that the components will be mounted to. A shadow root will be created on this container. If not provided, the components will be mounted to a `div` with the ID `elements-container`, and a shadow root will be created on that `div`. | | `defaultQueryClientOptions` | *object*, **optional** Initialization options of the ReactQuery client. See the [QueryClient Docs](https://tanstack.com/query/latest/docs/reference/QueryClient) for more info. | | `emotionCacheShadowRootContainer` | *ShadowRoot*, **optional** ***Deprecated*** A reference to a shadow root used for isolating the Elements style sheets, CSS resets, and emotion.js cache. | | `features` | *object*, **optional** A feature flag configuration object for turning features on and off. See [Configuring Elements Features](#configuring-elements-features) for a comprehensive list of features. | | `headers` | *object*, **optional** Optional HTTP headers to be sent with all requests. | | `locale` | *string*, **optional** Defaults to `en-us` | | `onApiError` | *object*, **optional** Callback function that will be executed whenever there is an error within the API. | | `onError` | *function*, **optional** An optional callback function to be invoked when an error occurs during a request to the API. | | `scope` | *string*, **optional** Element id to apply the theme, font family, and CSS reset. By default, the font will be applied to the body element, and the reset will be applied to the root HTML element.configured. | | `themeConfig` | *object*, **optional** The theme configuration object. Check out the [theming documentation](/apis/shipengine/docs/elements/elements-guide#theming) to learn more about theming your Elements integration. | ## Configuring Elements Features ```jsx features={{ globalFeatures: { enabledShipEngineCarriers: [ 'ups', 'stamps_com' ] enabledExternalCarriers: [ 'apc', 'asendia', 'better_trucks', 'courierpost', 'dpd', 'seko', 'ups', 'yodel', ], }, purchaseLabelFeatures: { ... }, shipmentSummaryFeatures: { ... }, accountSettingsFeatures: { ... }, labelsGridFeatures: { ... } }} ``` ### Global Features The following properties are configured within the `globalFeatures` property. | Params | Description | | --- | --- | | `enabledExternalCarriers` | *string[]*, **optional** List external carrier codes for carriers that can be registered through the [Connect External Carrier Element](/apis/shipengine/docs/elements/connect-external-carrier). If this is omitted, external carriers cannot be registered. See the [carriers section](/apis/shipengine/docs/elements/getting-started#carriers-in-elements) in the getting started guide for more information. **IMPORTANT:** If you exclude this property, or set the value to an empty array without including any supported carrier codes, users will not be able to view and connect External Carriers in the [Account Settings Element.](/apis/shipengine/docs/elements/account-settings/account-settings) or the [Manage External Carriers Element](/apis/shipengine/docs/elements/account-settings/manage-external-carriers) | | `enabledShipEngineCarriers` | *string[]*, **optional** List of ShipEngine carrier codes for carriers that can be registered through the [Onboarding Element](/apis/shipengine/docs/elements/connect-external-carrier). See the [carriers section](/apis/shipengine/docs/elements/getting-started#carriers-in-elements) in the getting started guide for more information. ** IMPORTANT: ** If you exclude this property, or set the value to an empty array without including any supported carrier codes, users will encounter an error that will prevent them from advancing through the onboarding process within the [Onboarding Element](/apis/shipengine/docs/elements/onboarding/onboarding) and will not be able to access the [Carrier Services Element](/apis/shipengine/docs/elements/account-settings/carrier-services). | | `poweredByShipEngine` | *boolean*, **optional** Enables the `Powered by ShipEngine` logo in the footer various elements. | > **NOTE:** Global features are set within the features prop of the Elements Provider and **cannot** be overridden within Element specific feature props. ### Element specific Features We recommend configuring the features you want to use in the Elements Provider or the SDK constructor for the Element. However, if you need to override features for a specific Element, you can use the feature prop for that Element, provided the Element supports it. | Params | Description | | --- | --- | | `purchaseLabelFeatures` | *string[]*, **optional** See [Purchase Label Features](/apis/shipengine/docs/elements/label-workflow/purchase-label#features) for a comprehensive list. | | `shipmentSummaryFeatures` | *string[]*, **optional** See [Shipment Summary Features](/apis/shipengine/docs/elements/label-workflow/shipment-summary#features) for a comprehensive list. | | `accountSettingsFeatures` | *string[]*, **optional** See [Account Settings Features](/apis/shipengine/docs/elements/account-settings/account-settings) for a comprehensive list. | | `labelsGridFeatures` | *string[]*, **optional** See [Labels Grid Features](/apis/shipengine/docs/elements/label-workflow/labels-grid) for a comprehensive list. | ## Creating Shipments If you wish to purchase a label using pre-populated values in the PurchaseLabel forms, the recommended way to define the shipment values is to create a new shipment using the ShipEngine API, and then pass the new Shipment ID to the PurchaseLabel or LabelWorkflow Element. The [@shipengine/react-api](https://www.npmjs.com/package/@shipengine/react-api) package required by Elements includes hooks that can be used to perform API operations such as creating shipments. Note that these hooks must be used from a component within the context of your `` See the example below: ```jsx import { useState, useEffect } from 'react'; import { useCreateShipment, PurchaseLabel, Currency, } from '@shipengine/elements'; export function CreateShipmentExample() { const [shipmentId, setShipmentId] = useState(''); const { mutateAsync: apiCreateShipment } = useCreateShipment(); useEffect(() => { async function createNewShipment() { const response = await apiCreateShipment({ shipTo: { name: 'Benjamin Biggs', phone: '+44 44 4444 4444', addressLine1: "Dean's Yard", cityLocality: 'London', stateProvince: '', postalCode: 'SW1P 3PA', countryCode: 'UK', }, shipFrom: { name: 'John Doe', companyName: 'Example Corp', phone: '333-333-3333', addressLine1: '4301 Bull Creek Rd', cityLocality: 'Austin', stateProvince: 'TX', postalCode: '78731', countryCode: 'US', }, packages: [ { packageCode: 'package', weight: { value: 20, unit: 'ounce' }, dimensions: { height: 6, width: 12, length: 24, unit: 'inch' }, products: [ { description: 'Pizza', quantity: 2, value: { currency: Currency.USD, amount: 20, }, sku: '1234ABCD', harmonizedTariffCode: '1905.90.9060', countryOfOrigin: 'US', }, ], }, ], }); if (!response.hasErrors) { setShipmentId(response.shipments[0].shipmentId); } } if (!shipmentId) { createNewShipment(); } }, [shipmentId, apiCreateShipment]); return <>{shipmentId && }; } ``` Only the `shipTo` and `shipFrom` properties are required; The rest may be left blank to be filled in by the user in the Element. The `packages.products` array is used for Customs information, and is not generally required for local shipments. For more information on the available fields within the Shipment object, see the [ShipEngine API documentation](https://shipengine.github.io/shipengine-openapi/#operation/create_shipments). For additional functionality provided by the ShipEngine API React Hooks provided by Elements, see the [Shipengine Elements API Clients documentation](https://elements-api-sdk-docs.shipengine.com/modules/_shipengine_react_api.html).