Skip to main content

React Elements SDK

React Elements SDK

basis-theory-react

Basis Theory React is an open source package designed to allow you to easily integrate Basis Theory JS SDK and Elements features in your React solution.

This section provides specific documentation for how to initialize a BasisTheory instance using Hooks, pass it to your component tree with Context and then declare Elements Components in your code use the underlying Element.

Creating, mounting, updating and unmounting Elements is as simple as declaring them as a typical React Components and passing props.

Before You Begin

This SDK requires the use of an API Key associated with a Public Application, which only allows token:create or token:update permissions to mitigate the risk that these API keys may be publicly exposed within your frontend applications.

To create one, login into our Portal and create a new "Public" Application with the permissions you require.

Considerations

Basis Theory React uses conventional camel case for most methods and converts these properties to snake case when sending requests to the API. One notable exception to this is the Tokenize method which uses snake case for the request body.

Installation

npm install --save @basis-theory/basis-theory-react
You don't need to install @basis-theory/basis-theory-js separately when using our React package, unless you need to direct import a capability from it.
The Basis Theory JS React Elements SDK >1.12.1 is not compatible with Create React App v5.0.0 or above due to a known issue.

Initialization

useBasisTheory

The useBasisTheory hook makes it easy to initialize the SDK or retrieve a previously initialized instance of it.

import { CardElement, useBasisTheory } from "@basis-theory/basis-theory-react";

const App = () => {
// creates a new instance of BasisTheory class
const { bt, error } = useBasisTheory("<API_KEY>", { elements: true });

// instance stays undefined during initialization
if (bt) {
// able to call BasisTheory methods
}

if (error) {
// initialization error
}

return <CardElement bt={bt} />;
};

useBasisTheory returns an object containing:

AttributeTypeDescription
btReact Elements SDK | undefinedAn instance of the React Elements SDK.
errorany | undefinedHolds any initialization errors (e.g. bad API key).
bt stays undefined during initialization, so you don't have to deal with Promise handling in your components code.

BasisTheoryProvider

This Context Provider shares an instance of the React Elements SDK to your component tree, making it available for Elements Components or other custom components.

import {
BasisTheoryProvider,
TextElement,
useBasisTheory,
} from "@basis-theory/basis-theory-react";

const App = () => {
// creates a new instance of BasisTheory class
const { bt } = useBasisTheory("<API_KEY>", { elements: true });

if (bt) {
// able to call BasisTheory methods
}

return (
<BasisTheoryProvider bt={bt}>
<MyComponent />
</BasisTheoryProvider>
);
};

const MyComponent = () => {
// calling this hook with no attributes grabs the instance from Context
const { bt } = useBasisTheory();

if (bt) {
// able to call BasisTheory methods
}

return <TextElement id="myInput" />; // Element will also grab it from the Context
};
Elements Components will prioritize the Basis Theory SDK instance passed to it's own bt property over an instance passed in to a parentBasisTheoryProvider.

Using Refs

Refs are a way to access DOM nodes or React component instances.

refs are utilized to store or receive (in the case of a callback ref) the underlying Basis Theory Elements instance, to tokenize their value or call one of its methods.

import { useRef } from "react";
import {
BasisTheoryApiError,
BasisTheoryValidationError,
TextElement,
useBasisTheory,
} from "@basis-theory/basis-theory-react";

const ssnMask = [/\d/, /\d/, /\d/, "-", /\d/, /\d/, "-", /\d/, /\d/, /\d/, /\d/];

const MyForm = () => {
const { bt } = useBasisTheory("<API_KEY>", { elements: true });
const fullNameRef = useRef(null);
const ssnRef = useRef(null);

const submit = async () => {
const fullName = fullNameRef.current;
const ssn = ssnRef.current;

try {
const tokens = await bt.tokenize({
fullName,
ssn,
});
} catch (error) {
if (error instanceof BasisTheoryValidationError) {
// check error details
} else if (error instanceof BasisTheoryApiError) {
// check error data or status
}
}
};

return (
<BasisTheoryProvider bt={bt}>
<TextElement
id="fullName"
ref={fullNameRef}
placeholder="Full name"
aria-label="Full name"
/>
<TextElement
id="ssn"
ref={ssnRef}
placeholder="SSN"
aria-label="Social Security Number"
mask={ssnMask}
transform={/[-]/}
/>
<div>
<button type="submit" onClick={submit} disabled={!bt}>
Submit
</button>
</div>
</BasisTheoryProvider>
);
};

When using Typescript, you can type-cast the element ref to safely to a specific Elements Component type.

import { useRef } from "react";
import type { CardExpirationDateElement } from "@basis-theory/basis-theory-react/types";

const expirationDateRef = useRef(null);

expirationDateRef.current.month(); // Error TS2551: property doesn't exist

const expirationDateRef = useRef < CardExpirationDateElement > null;

expirationDateRef.current.month(); // no error

Deprecated Features

The following table lists deprecated features and their respective shutdown date.

FeatureDeprecatedShutdown DateDetails
getElement methodAugust 25, 2022November 15, 2022getElement method will be removed in an upcoming release. Instead, please use refs