Skip to main content

Element Lifecycle

Understanding the lifecycle of Elements is important for properly creating, mounting and updating them in your application.

Element Lifecycle Overview

Elements go through several stages in their lifecycle:

  1. Initialization - Creating the BasisTheory instance
  2. Creation - Creating an Element instance
  3. Mounting - Attaching the Element to the DOM
  4. Updating - Changing Element properties

Initialization

The first step is initializing the BasisTheory instance:

import { basistheory } from "@basis-theory/web-elements";

// Async initialization
const bt = await basistheory("<PUBLIC_API_KEY>");

Creation

After initialization, you can create Element instances:

// Create a text element
const textElement = bt.createElement('text', {
targetId: 'my-text-element',
placeholder: 'Full Name'
});

// Create a card element
const cardElement = bt.createElement('card', {
targetId: 'my-card-element'
});

Mounting

Elements must be mounted to the DOM to be interactive:

// Mount elements to DOM containers
textElement.mount('#text-container');
cardElement.mount('#card-container');

// You can listen for the 'ready' event to know when mounting is complete
textElement.on('ready', () => {
console.log('Text element is mounted and ready');
});

Updating

You can update Element properties after creation:

// Update properties
textElement.update({
placeholder: 'Enter your full name',
disabled: false,
style: {
base: {
color: '#333333'
}
}
});

// Get the current state
const state = textElement.getState();
console.log('Is element complete?', state.complete);

Multiple Elements

Managing multiple elements is straightforward:

// Create multiple elements
const nameElement = bt.createElement('text', { targetId: 'name' });
const cardNumberElement = bt.createElement('cardNumber', { targetId: 'cardNumber' });
const expirationElement = bt.createElement('cardExpirationDate', { targetId: 'expiration' });
const cvcElement = bt.createElement('cardVerificationCode', { targetId: 'cvc' });

// Mount all elements
Promise.all([
nameElement.mount('#name-container'),
cardNumberElement.mount('#card-number-container'),
expirationElement.mount('#expiration-container'),
cvcElement.mount('#cvc-container')
]).then(() => {
console.log('All elements mounted');
});

// Retrieve elements by ID later
const name = bt.getElement('name');
const cardNumber = bt.getElement('cardNumber');

For optimal performance, it's generally better to reuse the same BasisTheory instance across your application rather than creating and tearing down instances repeatedly.

Troubleshooting Lifecycle Issues

Elements may sometimes disappear or fail to mount properly due to DOM lifecycle issues or environment specific constraints. If you encounter problems with Elements unexpectedly disappearing, not mounting, or timing out during initialization, refer to our troubleshooting guide for detailed solutions.