# ShipEngine is becoming ShipStation API

Over the next few months you'll notice the ShipEngine website, documentation portal, and dashboard being rebranded as ShipStation API. For our ShipEngine customers, you don't need to take any action or change any of your integrations in any way. All endpoints will remain the same and continue to function as they always have.

To learn more about what's coming, review our [New ShipStation API page](/content/docs/new-shipstation-api/index.html).

# Elements SDK

The Elements SDK is a JavaScript SDK for implementing ShipEngine Elements. You can install it via NPM or access it through our CDN.

## Quick Start

```bash
npm install @shipengine/elements-sdk
```

### 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 CDN

The ShipEngine Elements SDK can be included in any page by loading the bundle directly from the Elements CDN. If desired, you may specify a particular version of the SDK by using the following filename format:

```text
https://cdn.shipengine.com/shipengine-elements-sdk.<major_version>.<minor-version>.<patch-version>.mjs
```

You may omit any level of version number to always load the latest at that level. For example, `shipengine-elements-sdk.1.2.34.mjs` will pull version 1.2.34, while `shipengine-elements-sdk.1.mjs` will pull the latest minor and patch version for major version 1.

```javascript
import { ElementsSDK } from 'https://cdn.shipengine.com/shipengine-elements-sdk.mjs';

// or

<script src="https://cdn.shipengine.com/shipengine-elements-sdk.mjs"></script>
```

## Initialize Elements

You'll need to use the Elements SDK class constructor to initialize Elements. This constructor has three arguments:

1. **Token Callback Function (required):** This function, a key component of the Elements SDK, fetches and refreshes the tokens used by Elements. Check out the [Elements Getting Started guide](/content/docs/elements/getting-started/index.html) for more detailed information about generating Elements tokens.
2. **Initialization Parameters (optional):** This object allows you to customize various aspects of the Elements SDK. It's optional; See the [initialization parameters section](/content/docs/elements/elements-sdk/#initialization-parameters/index.html)
3. **Container (optional):** An HTML ID or HTML element that the Elements React root and CSS reset will be mounted to. The SDK uses a shadow root to isolate its CSS styles from the rest of your application, preventing conflicts and ensuring consistent styling. If you provide a container, the SDK will create a shadow root on that container and render the elements within it. If you don't provide a container, the SDK will create a new container element with a shadow root and append it to the document body.

```javascript
const elements = new ElementsSDK(
  getToken,
  {
    onError: (err: Error) => console.error(err),
    baseURL: 'https://elements.shipengine.com',
    themeConfig: themeConfig,
    locale: 'en-US',
    features: {
      globalFeatures: {
        enabledShipEngineCarriers: ['ups', 'stamps_com'],
        enabledExternalCarriers: [
          'apc',
          'asendia',
          'better_trucks',
          'courierpost',
          'dpd',
          'seko',
          'ups',
          'yodel',
        ],
      },
    },
  },
  'elementsRoot'
);
```

#### Initialization Parameters

| Args/Props | Description |
| --- | --- |
| `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` |
| `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](/content/docs/elements/elements-sdk/#configuring-elements-features/index.html) 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. |
| `themeConfig` | _object_, **optional** The theme configuration object. Check out the [theming documentation](/content/docs/elements/elements-guide/#theming/index.html) to learn more about theming your Elements integration. |

## Configuring Elements Features

```javascript
features={{
        globalFeatures: {
          enabledShipEngineCarriers: [
            'ups',
            'stamps_com'
          ],
          enabledExternalCarriers: [
            'apc',
            'asendia',
            'better_trucks',
            'courierpost',
            'dpd',
            'seko',
            'ups',
            'yodel',
          ],
        },
          purchaseLabelFeatures: { ... },
          shipmentSummaryFeatures: { ... },
          accountSettingsFeatures: { ... },
          labelsGridFeatures: { ... }
      }}
```

### Global Features

| Params | Description |
| --- | --- |
| `enabledExternalCarriers` | _string\[\]_, **optional** List external carrier codes for carriers that can be registered through the [Connect External Carrier Element](/content/docs/elements/connect-external-carrier/index.html). If this is omitted, external carriers cannot be registered. |
| `enabledShipEngineCarriers` | _string\[\]_, **optional** List of ShipEngine carrier codes for carriers that can be registered through the [Onboarding Element](/content/docs/elements/connect-external-carrier/index.html). |
| `poweredByShipEngine` | _boolean_, **optional** Enables the `Powered by ShipEngine` logo in the footer various elements. |

### Element specific Features

| Params | Description |
| --- | --- |
| `purchaseLabelFeatures` | _string\[\]_, **optional** See [Purchase Label Features](/content/docs/elements/label-workflow/purchase-label/#purchase-label-features/index.html) for a comprehensive list. |
| `shipmentSummaryFeatures` | _string\[\]_, **optional** See [Shipment Summary Features](/content/docs/elements/label-workflow/shipment-summary/#shipment-summary-features/index.html) for a comprehensive list. |
| `accountSettingsFeatures` | _string\[\]_, **optional** See [Account Settings Features](/content/docs/elements/account-settings/#account-settings-features/index.html) for a comprehensive list. |
| `labelsGridFeatures` | _string\[\]_, **optional** See [Labels Grid Features](/content/docs/elements/labels-grid/index.html) for a comprehensive list. |

## Rendering Elements

#### elements.create(element)

| Params | Description |
| --- | --- |
| `element` | _string_, **required** The name of the Element to be created. |

### Elements

- `accountSettings`
- `carrierServices`
- `connectExternalCarrier`
- `labelLayout`
- `labelWorkFlow`
- `manageCarriers`
- `manageExternalCarriers`
- `manageFunding`
- `manageWarehouses`
- `onboarding`
- `paymentMethodSettings`
- `purchaseLabel`
- `shipmentSummary`
- `transactionHistory`
- `unitSettings`
- `voidLabel`
- `labelsGrid`

#### elements.destroy()

Removes Elements from the DOM and destroys it. A destroyed Element instance can not be re-activated or re-mounted to the DOM.

#### elements.getClient()

Returns an instance of the ShipEngine Elements API JavaScript client. This client can be used to interact directly with the ShipEngine API.

If no parameters are passed to `getClient()`, the client will be configured based off of the initialization parameters passed to the Elements SDK constructor. If desired, you may pass a token and configuration object to the `getClient()` method to specify a different configuration:

```javascript
const token = await getToken();
const apiClient = elements.getClient(token, {
  getToken,
  onApiError: myOtherErrorHandler,
});
```

#### Side Panel Methods (deprecated)

While working with the Elements SDK, you probably noticed methods for rendering individual Elements in a side panel. Methods like `onboardUser` or `purchaseLabel`, accessible via the Elements SDK class, have been deprecated in Elements v2 and will be removed in future versions.

## Element Render Methods

There are two ways to render Elements in your application:

- Mounting elements in a specified DOM node or,
- Opening the Elements in a pre-configured slide in drawer (Side Panel).

The Elements SDK allows you to place Elements in any container in your app, but the Elements were designed to look best at a viewport width of `440 to 800 pixels`.

#### element.mount(domElement, props)

Before you mount an Element, you must create a container DOM element. The `mount` method attaches your Element to the DOM. **`mount`** accepts either an ID Attribute (e.g., **`purchaseLabelId`**) or a DOM element as well as the Elements props. See the documentation for that Element for more information on its props.

```html
<div id="purchaseLabelId">
  <!-- Purchase Label Element will be inserted here. -->
</div>

<script>
  purchaseLabel.mount('purchaseLabelId');
</script>
```

#### element.update(props)

Updates the props for the element

```javascript
// updates the shipment Id of the purchase label element
purchaseLabel.update({ shipmentId: 'se-1198001' });
```

#### element.unmount()

Unmounts the Element from the DOM. Call the `element.mount()` method to re-attach it to the DOM.

```javascript
purchaseLabel.unmount();
```

#### element.renderSidePanel(props)

Renders the Element inside a side panel. The method accepts the Elements props as well as the props for the side panel that it is rendered in side of.

```javascript
purchaseLabel.renderSidePanel({
  elementProps: { shipmentId: 'se-11975001' },
  sidePanelHeaderProps: { title: 'Purchase a Label' },
  sidePanelProps: { position: 'left' },
});
```

#### element.closeSidePanel()

Closes the currently opened side panel.

```javascript
purchaseLabel.closeSidePanel();
```

## Creating Shipments

If you wish to purchase a label using pre-populated values in the Purchase label 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 Elements SDK provides an API client which can be used to generate the shipment using the same authentication token used by Elements. See the example below:

```javascript
const client = elements.getClient(await getToken());
const response = await client.shipments.create({
  ship_to: {
    name: 'Benjamin Biggs',
    phone: '+44 44 4444 4444',
    address_line1: "Dean's Yard",
    city_locality: 'London',
    postal_code: 'SW1P 3PA',
    country_code: 'UK',
  },
  ship_from: {
    name: 'John Doe',
    company_name: 'Example Corp',
    phone: '333-333-3333',
    address_line1: '4301 Bull Creek Rd',
    city_locality: 'Austin',
    state_province: 'TX',
    postal_code: '78731',
    country_code: 'US',
  },
  packages: [
    {
      weight: { value: 20, unit: 'ounce' },
      dimensions: { height: 6, width: 12, length: 24, unit: 'inch' },
      products: [
        {
          description: 'Pizza',
          quantity: 2,
          value: {
            currency: 'USD',
            amount: 20,
          },
          sku: '1234ABCD',
          harmonized_tariff_code: '1905.90.9060',
          country_of_origin: 'US',
        },
      ],
    },
  ],
});
const shipmentId = response.data.shipments[0].shipmentId;

const purchaseLabel = elements.create('purchaseLabel');
purchaseLabel.renderSidePanel({
  elementProps: {
    shipmentId: this.shipmentId,
  },
});
```

Only the `ship_to` and `ship_from` 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 Elements API Client, see the [ShipEngine Elements API Clients documentation](https://elements-api-sdk-docs.shipengine.com/modules/_shipengine_js_api.html).
