Introduction
Basis Theory Elements are simple, secure, developer-friendly inputs that empower consumers to collect sensitive data from their users directly to Basis Theory certified vault.
Think about it as a portal that we open within your site that allows users to seamlessly tokenize information and never notice they are interacting with our technology. Here is how we make it possible:
- Own your UX, by fully customizing how Elements are styled
- Inputs and forms are simple to use
- Able to interact with Elements as you do with native elements
Getting started
Before You Begin
If you don't have an account
To begin taking advantage of the Basis Theory platform, you’ll need to create an account and Tenant through our Portal.
If you have an account
Check out our API Reference documentation below, or go to our Getting Started section if you’re unsure of where to go next.
Install SDK
NPM
npm install --save @basis-theory/basis-theory-js
Yarn
yarn add @basis-theory/basis-theory-js
CDN
<!-- Including this tag will export a global/window "BasisTheory" variable -->
<script src="https://js.basistheory.com"></script>
You don't have to install Elements as a separate module or include additional script tags besides BasisTheory.js. It will dynamically load them from our secure domain, which enables us to keep the highest compliance standards (e.g. PCI compliance).
To install BasisTheory.js you can choose either our NPM module or CDN hosted bundle through a script
tag.
Content Security Policy
CSP
<head>
<meta
http-equiv="Content-Security-Policy"
content="frame-src https://elements.basistheory.com; script-src https://js.basistheory.com"
/>
</head>
Trusted Types
trustedTypes.createPolicy("default", {
createScriptURL: (input) => {
if (new URL(input).origin === "https://js.basistheory.com") {
return input;
}
return undefined;
}
});
If you have a CSP deployed in your website, you must include the following directives:
script-src
- https://js.basistheory.comframe-src
- https://elements.basistheory.com
If you are using Trusted Types, you must allow dynamic script loading from the https://js.basistheory.com origin. This should be done BEFORE initialization.
Common CSP Errors
The setup above is recommended to avoid errors similar to these:
Usage with TypeScript
Starting at 1.14.0
, BasisTheory.js bundles all TypeScript definitions for Elements features. You don't have to take any extra steps in order to use it.
If you can't upgrade past 1.13.1
, Basis Theory Elements offers unmaintained definitions for deprecated Elements features.
Permissions
Permissions offer fine-grained control over your Application's access to different aspects of your token infrastructure. We suggest limiting the scope of your Application to the least amount possible, and to not share them across your internal services.
Permissions are associated with every Application and can be configured when you create an Application or update an Application.
Elements Applications only allow create permissions, removing any risk that your API keys are stolen and used to access data.
Permission Types
Permission | Description |
---|---|
token:general:create |
Create tokens in the vault |
token:pci:create |
Create Card tokens |
token:bank:create |
Create Bank tokens |
Authentication
Elements use a specific type of Application key to allow access to the API. To create one, login into our Portal and create a new "Elements" Application with the permissions you require.
Limits
The Basis Theory API has rate limits applied to ensure the speed and consistency of our systems.
- Our Elements are restricted to 10 requests per IP, per second, per Application
- Our APIs are restricted to 100 requests per IP, per second, per Application
Error Codes
Error Code | Meaning |
---|---|
429 |
Request has been rate limited |
Initialize
CDN
<script>
// you can initialize it wherever it suits your workflow best
// here we are waiting for the window to load, to make sure BasisTheory instance
// has been injected in the window variable
window.addEventListener('load', async () => {
try {
// global/window variable BasisTheory is an instance, but requires initialization
await BasisTheory.init('test_1234567890', { elements: true });
// use Elements
} catch (e) {
// handle errors that could happen while loading elements script
}
});
</script>
Module
import { BasisTheory } from '@basis-theory/basis-theory-js';
// In this context BasisTheory is a class
const bt = await new BasisTheory().init('test_1234567890', { elements: true });
// use Elements
Initialize BasisTheory
with elements: true
so it dynamically loads Elements module.
Parameter | Required | Type | Description |
---|---|---|---|
apiKey |
true | string | The API Key used to identify an Application. |
options |
false | BasisTheoryInitOptions | Options for initializing the BasisTheory instance. |
Basis Theory Init Options
Attribute | Required | Type | Description |
---|---|---|---|
elements |
false | boolean | Boolean used to indicate whether the BasisTheory instance will have Elements capabilities. |
Element Types
Card Element
The "card"
element type features a one-liner credit card collector containing the following inputs:
- cardNumber
- expirationDate
- cvc
Text Element
The "text"
element type is a secure replacement for the <input>
tag and enables collecting user string
data.
Card Number Element
The "cardNumber"
element type renders a card number input and an optional card icon, featuring automatic brand detection, input validation
and masking.
Card Expiration Date Element
The "cardExpirationDate"
element type features a month/year formatted input with validation. The date must be between current month and 20 years in the future.
Card Verification Code Element
The "cardVerificationCode"
element type is used to collect the card security code.
Elements Instance
After initialization, Elements are available through BasisTheory
instance.
Create Element
var cardElement = BasisTheory.createElement('card', options);
var textElement = BasisTheory.createElement('text', { targetId: 'myInputId', ...options });
This lifecycle method returns a new instance of an element type.
Parameter | Required | Type | Description |
---|---|---|---|
type |
true | string | Type of the element you want to create |
options |
false | object | Options for customizing the element |
Mount Element
<div id="my-card"></div>
<script>
cardElement.mount('#my-card')
</script>
This lifecycle method attaches the element to the DOM, under a specific container.
Parameter | Required | Type | Description |
---|---|---|---|
selector |
true | string | CSS selector that matches the container where your element will be mounted |
Update Element
cardElement.update(options);
This lifecycle method updates the element options the element was initialized with. The values are merged into the previous options.
Parameter | Required | Type | Description |
---|---|---|---|
options |
false | object | Options for customizing the element |
Clear Element
cardElement.clear();
Clears the element input(s) value.
Unmount Element
cardElement.unmount();
This lifecycle method safely removes the element from the DOM, stopping any further communication with it.
Element Options
You can customize the behavior of your Elements using the following options:
Attribute | Required | Type | Updatable | Eligible Elements | Description |
---|---|---|---|---|---|
style |
false | object | true | All | Object used to customize the element appearance |
disabled |
false | boolean | true | All | Boolean used to set the disabled attribute of the input(s) |
targetId |
true | string | false | text cardNumber cardExpirationDate cardVerificationCode |
String used to identify your element |
placeholder |
false | string | true | text cardNumber cardExpirationDate cardVerificationCode |
String used to customize the placeholder attribute of the input |
aria-label |
false | string | true | text cardNumber cardExpirationDate cardVerificationCode |
String used to customize the aria-label attribute of the input |
mask |
false | array | false | text |
Array used to restrict and fill user input using regex and static strings |
transform |
false | RegExp | true | text |
RegExp object or array used to modify user input before tokenization |
password |
false | boolean | true | text |
Boolean used to set the text element input type as password |
iconPosition |
false | string | true | cardNumber |
String used to determine the position of the card element icon. Expected values are: left (default), right or none . |
cardBrand |
false | string | true | cardVerificationCode |
String used to determine proper input format and default placeholder/aria-label |
Style
var cardElement = BasisTheory.createElement('card', {
style: {
fonts: [
"https://fonts.googleapis.com/css2?family=Inter:ital,[email protected],200;0,300;0,400;0,600;0,700;0,900;1,200;1,300;1,400;1,600;1,700;1,900&display=swap"
],
base: {
color: "#fff",
fontWeight: 500,
fontFamily: '"Inter"',
fontSize: "16px",
fontSmooth: "antialiased",
"::placeholder": {
color: "#6b7294"
},
":disabled": {
backgroundColor: "#f0f0f4"
},
},
invalid: {
color: "#ffc7ee"
},
complete: {
color: "#1ad1db"
}
}
})
Elements are styled through the ElementStyle
object, which maps state variants and miscellaneous.
Attribute | Required | Type | Description |
---|---|---|---|
fonts |
false | array | Array of Google Fonts URLs |
base |
false | object | Base variant style - all other variant styles inherit from this one |
complete |
false | object | Variant style applied when the element input has valid value |
empty |
false | object | Variant style applied when the element input has no value |
invalid |
false | object | Variant style applied when the element input has invalid value |
You can customize the following pseudo-classes and pseudo-elements inside each variant using a nested object:
:hover
:focus
:disabled
::placeholder
::selection
Here is a complete list of the supported CSS properties:
- backgroundColor
- color
- fontFamily
- fontSize
- fontSmooth (we replace this with the user-agent alternate names automatically)
- fontStyle
- fontVariant
- fontWeight
- lineHeight
- letterSpacing
- textAlign
- padding
- textDecoration
- textShadow
- textTransform
Mask
var phoneNumberElement = BasisTheory.createElement('text', {
targetId: 'myPhoneNumberElement',
mask: ['(', /\d/, /\d/, /\d/, ')', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
})
Text elements can restrict and fill user input by using the mask
attribute. It consists of an array of RegExp
objects and strings, used to restrict and fill input, respectively. The position of each item in the mask array
corresponds to the restriction or fill used for that input's position. The length of the array determines how long an
input is allowed to be. For example, the mask for a US based phone number shown on the right will have the following
rules:
- The input must be at most 13 characters long
- Only digits are allowed in the 2-4, 6-8, 10-13 positions
- '(' will be filled in the 1 position
- ')' will be filled in the 5 position
- '-' will be filled in the 8 position
The mask will be displayed as the user is typing, and will be used as the value for tokenization performed with that text element. If the value does not satisfy the mask in its entirety, the field is considered incomplete. This is reflected in the on change events and will fail validation before tokenization.
Transform
var phoneNumberElement = BasisTheory.createElement('text', {
targetId: 'myPhoneNumberElement',
mask: ['(', /\d/, /\d/, /\d/, ')', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/],
transform: /[()-]/,
})
Text elements allow you to modify user input before tokenization through the
transform
attribute. It can be set as a RegExp
object, an array with a RegExp
object, or an array with a RegExp
object at the first index and a string at the second. It works by making use of the String replace
function. The RegExp
object and string defined will be used as the first and second argument for the replace
function,
respectively. If no string is defined, an empty string will be used as the second argument. For instance, the mask for a
US based phone number shown on the right will modify user input to look like this: (123)456-7890
. The transform
attribute, in this case, will modify the user input to remove (
, )
, and -
from the input. The resulting value is
1234567890
which will be what gets tokenized.
Card Brands
The following list maps supported Card Brands to their values:
Brand | Value |
---|---|
American Express | american-express |
Diners Club | diners-club |
Discover | discover |
Elo | elo |
Hiper | hiper |
HiperCard | hipercard |
JCB | jcb |
Maestro | maestro |
Mastercard | mastercard |
MIR | mir |
UnionPay | unionpay |
Visa | visa |
Unknown | unknown |
Element Events
var subscription = cardElement.on('event-type', (event) => {
// handle event
});
subscription.unsubscribe(); // stops listening to the event type
You can communicate with Elements by listening to events. When you subscribe to an event, you'll get back a Subscription that you can unsubscribe if/when it fits your workflow.
On Ready
cardElement.on('ready', () => {
// handle ready event
})
This event is triggered when the element has rendered and user is able to start interacting with it.
On Change
cardElement.on('change', (changeEvent) => {
if (changeEvent.complete) {
// enable submit button
} else {
// disable submit button
// present validation message
}
})
This event is triggered whenever element's value(s) change. For example, if the user types data that doesn't change the state of a field between valid/invalid or empty/filled, you shouldn't expect the event to trigger.
Parameter | Required | Type | Description |
---|---|---|---|
event |
true | "change" | The event type to listen to. |
handler |
true | function | Callback function to be called when the event is fired. Takes in a ChangeEvent. |
ChangeEvent
{
"complete": false,
"empty": false,
"errors": [
{...},
{...}
],
"cardBrand": "american-express"
}
Attribute | Type | Eligible Elements | Description |
---|---|---|---|
complete |
boolean | All | If the element value is well-formed and is ready to be submitted. |
empty |
boolean | All | Whether the element is empty. Multi-input Elements will be empty only if all inputs are. |
errors |
array | All | Array of FieldError. |
cardBrand |
string | card cardNumber |
(Optional) The credit card brand (e.g. 'american-express' , 'visa' , 'unknown' ). The value defaults to 'unknown' until a card brand is recognized. |
FieldError
{
"targetId": "cardNumber",
"type": "invalid"
}
Attribute | Type | Description |
---|---|---|
targetId |
string | Input id that triggered the error. Values vary per element type. |
type |
"invalid" or "incomplete" | Type of the error. |
On Focus
cardElement.on('focus', (focusEvent) => {
})
Triggered when an element input is focused.
Parameter | Required | Type | Description |
---|---|---|---|
event |
true | "focus" | The event type to listen to. |
handler |
true | function | Callback function to be called when the event is fired. Takes in a FocusEvent. |
FocusEvent
{
"targetId": "cardNumber"
}
Attribute | Type | Description |
---|---|---|
targetId |
string | Input id that triggered the event. Values vary per element type. |
On Blur
cardElement.on('blur', (blurEvent) => {
})
Triggered when an element input focus is lost.
Parameter | Required | Type | Description |
---|---|---|---|
event |
true | "blur" | The event type to listen to. |
handler |
true | function | Callback function to be called when the event is fired. Takes in a BlurEvent. |
BlurEvent
{
"targetId": "cardNumber"
}
Attribute | Type | Description |
---|---|---|
targetId |
string | Input id that triggered the event. Values vary per element type. |
On Keydown
cardElement.on('keydown', (keydownEvent) => {
})
Triggered when user hits a special key inside an element input.
Parameter | Required | Type | Description |
---|---|---|---|
event |
true | "keydown" | The event type to listen to. |
handler |
true | function | Callback function to be called when the event is fired. Takes in a KeydownEvent. |
KeydownEvent
{
"targetId": "cardNumber",
"key": "Enter",
"ctrlKey": false,
"altKey": false,
"shiftKey": false,
"metaKey": false
}
Attribute | Type | Description |
---|---|---|
targetId |
string | Input targetId that triggered the event. Values vary per element type. |
key |
Escape or Enter | Key pressed by the user. |
ctrlKey |
boolean | Flag indicating control key was pressed when the event occurred. |
altKey |
boolean | Flag indicating alt key was pressed when the event occurred. |
shiftKey |
boolean | Flag indicating shift key was pressed when the event occurred. |
metaKey |
boolean | Flag indicating meta key was pressed when the event occurred. |
Tokenization
Create generic token
BasisTheory.tokens.create({
type: 'token',
data: {
sensitiveData: sensitiveDataElement,
nonSensitiveData: 'plainText', // see warning on plain text data
otherData: {
someInteger: 20,
someBoolean: false,
},
someOtherData: ['plainText1', 'plainText2'],
},
metadata: {
nonSensitiveField: 'nonSensitiveValue'
}
}).then((token) => {
console.log(token.id); // token to store
console.log(JSON.stringify(token)); // full response
});
Create card token
BasisTheory.tokens.create({
type: 'card',
data: cardElement,
}).then((token) => {
console.log(token.id); // token to store
console.log(JSON.stringify(token.data)); // redacted card data
});
Create bank token
BasisTheory.tokens.create({
type: 'bank',
data: {
routingNumber: routingNumberElement,
accountNumber: accountNumberElement,
}
}).then((token) => {
console.log(token.id); // token to store
console.log(JSON.stringify(token.data)); // redacted bank data
});
Tokenize data
BasisTheory.tokenize({
card1: {
type: 'card',
data: cardElement,
},
card2: {
type: 'card',
data: {
number: cardNumberElement,
expiration_month: cardExpirationDateElement.month(),
expiration_year: cardExpirationDateElement.year(),
cvc: cardVerificationCodeElement
},
},
sensitiveData: sensitiveDataElement,
nonSensitiveData: 'plainText', // see warning on plain text data
otherData: {
someInteger: 20,
someBoolean: false,
},
someOtherData: ['plainText1', 'plainText2'],
}).then((tokens) => {
console.log(tokens.card1.id, tokens.card2.id, tokens.sensitiveData); // token to store
console.log(JSON.stringify(tokens)); // full response
});
Elements' values can be securely tokenized using tokens.create
and tokenize
services. To do that, simply pass the Element instance (or one of its data parsing methods) in the payload.
You can fetch this same data later with Get a Token API
Data Parsing
The following methods can be called to parse the Element value for proper tokenization.
Name | Resulting Type | Eligible Elements | Description |
---|---|---|---|
month |
number | cardExpirationDate | Resolves to the one-based month value of the input date |
year |
number | cardExpirationDate | Resolves to the four-digit year value of the input date |
Errors
Elements services could throw an error based on client-side validations or if the server rejects the request.
BasisTheoryValidationError
BasisTheoryValidationError
{
details: {
card1: {
number: {
type: 'invalid'
},
cvc: {
type: 'incomplete'
}
},
card2: {
}
},
validation: [] // deprecated
}
Attribute | Type | Description |
---|---|---|
name |
string | Error name, always 'BasisTheoryValidationError' . |
details |
object | Maps payload properties to their respective element's validation problems. |
validation |
array | Deprecated in favor of details. Array of FieldError, in case of client-side error. |
BasisTheoryApiError
BasisTheoryApiError
{
data: {
// API response body
},
status: 400
}
Attribute | Type | Description |
---|---|---|
name |
string | Error name, always 'BasisTheoryApiError' . |
data |
object | Response body sent from the server. |
status |
number | Response HTTP status. |
Handling services errors
import {
BasisTheoryApiError,
BasisTheoryValidationError
} from '@basis-theory/basis-theory-js/common';
BasisTheory.tokenize({
card1: {
type: 'card',
data: cardElement1
},
card2: {
type: 'card',
data: cardElement2
},
ssn: textElement
}).catch((error) => {
if (error instanceof BasisTheoryValidationError) {
// check error details
} else if (error instanceof BasisTheoryApiError) {
// check error data or status
}
});
Deprecations
Deprecated Services
The following table lists deprecated services and their respective shutdown date.
Service | Deprecated | Shutdown Date | Details |
---|---|---|---|
storeCreditCard |
December 10, 2021 | April 22, 2022 | storeCreditCard service has been removed. Instead, please use Tokenization Services. |
atomicCards |
April 22, 2022 | July 22, 2022 | atomicCards service will be removed in an upcoming release. Instead, please use Tokenization Services. |
atomicBanks |
April 22, 2022 | July 22, 2022 | atomicBanks service will be removed in an upcoming release. Instead, please use Tokenization Services. |
Deprecated Features
The following table lists deprecated features and their respective shutdown date.
Feature | Deprecated | Shutdown Date | Details |
---|---|---|---|
validation property in error |
April 22, 2022 | July 22, 2022 | validation property in errors will be removed in an upcoming release. Instead, please use details |
React Package
NPM
npm install --save @basis-theory/basis-theory-react
Yarn
yarn add @basis-theory/basis-theory-react
useBasisTheory
The useBasisTheory
hook makes it easy to initialize the SDK or retrieve a previously initialized instance of it.
It returns an object containing:
Attribute | Type | Description |
---|---|---|
bt |
BasisTheoryReact | undefined | BasisTheoryReact instance. Note: this stays undefined during BasisTheory initialization, so you don't have to deal with Promise handling in your components code. |
error |
any | undefined | Holds any initialization errors (e.g. bad API key). |
Initialize
import {
useBasisTheory
} from '@basis-theory/basis-theory-react';
const App = () => {
// creates a new instance of BasisTheory class
const { bt, error } = useBasisTheory('test_1234567890', { elements: true });
// instance stays undefined during initialization
if (bt) {
// able to call BasisTheory methods
}
if (error) {
// initialization error
}
return <MyComponent />;
}
Calling the useBasisTheory
hook with parameters creates a new instance of BasisTheoryReact
class and initializes it automatically.
Parameter | Required | Type | Description |
---|---|---|---|
apiKey |
true | string | The API Key used to identify an Application. |
options |
false | BasisTheoryInitOptions | Options for initializing the BasisTheoryReact instance. |
Retrieve from Context
Calling the useBasisTheory
hook with no parameters will retrieve the BasisTheoryReact
instance from the Context
. See BasisTheoryProvider.
BasisTheoryProvider
import {
BasisTheoryProvider,
TextElement,
useBasisTheory
} from '@basis-theory/basis-theory-react';
const App = () => {
// creates a new instance of BasisTheory class
const { bt } = useBasisTheory('test_1234567890', { 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
}
This Context Provider shares a BasisTheoryReact
instance to your component tree, making it available for Basis Theory Elements or other custom components.
Property | Required | Type | Description |
---|---|---|---|
bt |
false | BasisTheoryReact | Instance to be provided in the context. Note: this is not required because initialization happens asynchronously. See useBasisTheory . |
CardElement
Using
BasisTheoryProvider
import {
BasisTheoryProvider,
CardElement,
useBasisTheory
} from '@basis-theory/basis-theory-react';
const App = () => {
// creates a new instance of BasisTheory class
const { bt } = useBasisTheory('test_1234567890', { elements: true });
return <BasisTheoryProvider bt={bt}>
<MyComponent />
</BasisTheoryProvider>;
}
const MyComponent = () => {
return <CardElement id="myCard" /> ; // Element will grab instance from the Context
}
Using
bt
property
import {
CardElement,
useBasisTheory
} from '@basis-theory/basis-theory-react';
const MyComponent = () => {
// creates a new instance of BasisTheory class
const { bt } = useBasisTheory('test_1234567890', { elements: true });
return <CardElement id="myCard" bt={bt} /> ;
}
The CardElement
component features a full credit card form, wrapping the card element type functionality and taking care of the React lifecycle.
Property | Required | Type | Updatable | Description |
---|---|---|---|---|
id |
true | string | false | String identifier used to retrieve the Element instance for tokenization. |
bt |
false | BasisTheoryReact | false | Instance used by the Element. Note: this is not required because Elements are capable of consuming the instance from Context. See BasisTheoryProvider . |
style |
false | object | true | Object used to customize the element appearance |
disabled |
false | boolean | true | Boolean used to set the disabled attribute of the input(s) |
onReady |
false | function | true | Event Listener. See On Ready |
onChange |
false | function | true | Event Listener. See On Change |
onFocus |
false | function | true | Event Listener. See On Focus |
onBlur |
false | function | true | Event Listener. See On Blur |
onKeyDown |
false | function | true | Event Listener. See On Keydown |
TextElement
Using
BasisTheoryProvider
import {
BasisTheoryProvider,
TextElement,
useBasisTheory
} from '@basis-theory/basis-theory-react';
const App = () => {
// creates a new instance of BasisTheory class
const { bt } = useBasisTheory('test_1234567890', { elements: true });
return <BasisTheoryProvider bt={bt}>
<MyComponent />
</BasisTheoryProvider>;
}
const MyComponent = () => {
return <TextElement id="myInput" /> ; // Element will grab instance from the Context
}
Using
bt
property
import {
TextElement,
useBasisTheory
} from '@basis-theory/basis-theory-react';
const MyComponent = () => {
// creates a new instance of BasisTheory class
const { bt } = useBasisTheory('test_1234567890', { elements: true });
return <TextElement id="myInput" bt={bt} /> ;
}
The TextElement
component features a regular text input for collecting any input data, by wrapping the text element type functionality and taking care of the React lifecycle.
Property | Required | Type | Updatable | Description |
---|---|---|---|---|
id |
true | string | false | String identifier used to retrieve the Element instance for tokenization. Note: This is passed through to the targetId option. |
bt |
false | BasisTheoryReact | false | Instance used by the Element. Note: this is not required because Elements are capable of consuming the instance from Context. See BasisTheoryProvider . |
style |
false | object | true | Object used to customize the element appearance |
disabled |
false | boolean | true | Boolean used to set the disabled attribute of the input(s) |
mask |
false | array | false | Array used to restrict and fill user input using regex and static strings |
transform |
false | RegExp | true | RegExp object or array used to modify user input before tokenization |
placeholder |
false | string | true | String used to customize the placeholder attribute of the input |
aria-label |
false | string | true | String used to customize the aria-label attribute of the input |
password |
false | boolean | true | Boolean used to set the text element input type as password |
onReady |
false | function | true | Event listener. See On Ready |
onChange |
false | function | true | Event listener. See On Change |
onFocus |
false | function | true | Event listener. See On Focus |
onBlur |
false | function | true | Event listener. See On Blur |
onKeyDown |
false | function | true | Event listener. See On Keydown |
CardNumberElement
Using
BasisTheoryProvider
import {
BasisTheoryProvider,
CardNumberElement,
useBasisTheory
} from '@basis-theory/basis-theory-react';
const App = () => {
// creates a new instance of BasisTheory class
const { bt } = useBasisTheory('test_1234567890', { elements: true });
return <BasisTheoryProvider bt={bt}>
<MyComponent />
</BasisTheoryProvider>;
}
const MyComponent = () => {
return <CardNumberElement id="cardNumber" /> ; // Element will grab instance from the Context
}
Using
bt
property
import {
CardNumberElement,
useBasisTheory
} from '@basis-theory/basis-theory-react';
const MyComponent = () => {
// creates a new instance of BasisTheory class
const { bt } = useBasisTheory('test_1234567890', { elements: true });
return <CardNumberElement id="cardNumber" bt={bt} /> ;
}
The CardNumberElement
component features a card number input, by wrapping the cardNumber
element type functionality and taking care of the React lifecycle.
Property | Required | Type | Updatable | Description |
---|---|---|---|---|
id |
true | string | false | String identifier used to retrieve the Element instance for tokenization. Note: This is passed through to the targetId option. |
bt |
false | BasisTheoryReact | false | Instance used by the Element. Note: this is not required because Elements are capable of consuming the instance from Context. See BasisTheoryProvider . |
style |
false | object | true | Object used to customize the element appearance |
disabled |
false | boolean | true | Boolean used to set the disabled attribute of the input(s) |
iconPosition |
false | string | true | String used to determine the position of the card brand icon. Expected values are: left (default), right or none . |
placeholder |
false | string | true | String used to customize the placeholder attribute of the input |
aria-label |
false | string | true | String used to customize the aria-label attribute of the input |
onReady |
false | function | true | Event listener. See On Ready |
onChange |
false | function | true | Event listener. See On Change |
onFocus |
false | function | true | Event listener. See On Focus |
onBlur |
false | function | true | Event listener. See On Blur |
onKeyDown |
false | function | true | Event listener. See On Keydown |
CardExpirationDateElement
Using
BasisTheoryProvider
import {
BasisTheoryProvider,
CardExpirationDateElement,
useBasisTheory
} from '@basis-theory/basis-theory-react';
const App = () => {
// creates a new instance of BasisTheory class
const { bt } = useBasisTheory('test_1234567890', { elements: true });
return <BasisTheoryProvider bt={bt}>
<MyComponent />
</BasisTheoryProvider>;
}
const MyComponent = () => {
return <CardExpirationDateElement id="cardExpirationDate" /> ; // Element will grab instance from the Context
}
Using
bt
property
import {
CardExpirationDateElement,
useBasisTheory
} from '@basis-theory/basis-theory-react';
const MyComponent = () => {
// creates a new instance of BasisTheory class
const { bt } = useBasisTheory('test_1234567890', { elements: true });
return <CardExpirationDateElement id="cardExpirationDate" bt={bt} /> ;
}
The CardExpirationDateElement
component features a card expiration date input, by wrapping the cardExpirationDate
element type functionality and taking care of the React lifecycle.
Property | Required | Type | Updatable | Description |
---|---|---|---|---|
id |
true | string | false | String identifier used to retrieve the Element instance for tokenization. Note: This is passed through to the targetId option. |
bt |
false | BasisTheoryReact | false | Instance used by the Element. Note: this is not required because Elements are capable of consuming the instance from Context. See BasisTheoryProvider . |
style |
false | object | true | Object used to customize the element appearance |
disabled |
false | boolean | true | Boolean used to set the disabled attribute of the input(s) |
placeholder |
false | string | true | String used to customize the placeholder attribute of the input |
aria-label |
false | string | true | String used to customize the aria-label attribute of the input |
onReady |
false | function | true | Event listener. See On Ready |
onChange |
false | function | true | Event listener. See On Change |
onFocus |
false | function | true | Event listener. See On Focus |
onBlur |
false | function | true | Event listener. See On Blur |
onKeyDown |
false | function | true | Event listener. See On Keydown |
CardVerificationCodeElement
Using
BasisTheoryProvider
import {
BasisTheoryProvider,
CardVerificationCodeElement,
useBasisTheory
} from '@basis-theory/basis-theory-react';
const App = () => {
// creates a new instance of BasisTheory class
const { bt } = useBasisTheory('test_1234567890', { elements: true });
return <BasisTheoryProvider bt={bt}>
<MyComponent />
</BasisTheoryProvider>;
}
const MyComponent = () => {
return <CardVerificationCodeElement id="cardVerificationCode" /> ; // Element will grab instance from the Context
}
Using
bt
property
import {
CardVerificationCodeElement,
useBasisTheory
} from '@basis-theory/basis-theory-react';
const MyComponent = () => {
// creates a new instance of BasisTheory class
const { bt } = useBasisTheory('test_1234567890', { elements: true });
return <CardVerificationCodeElement id="cardVerificationCode" bt={bt} /> ;
}
The CardVerificationCodeElement
component features a card security code input, by wrapping the cardVerificationCode
element type functionality and taking care of the React lifecycle.
Property | Required | Type | Updatable | Description |
---|---|---|---|---|
id |
true | string | false | String identifier used to retrieve the Element instance for tokenization. Note: This is passed through to the targetId option. |
bt |
false | BasisTheoryReact | false | Instance used by the Element. Note: this is not required because Elements are capable of consuming the instance from Context. See BasisTheoryProvider . |
style |
false | object | true | Object used to customize the element appearance |
disabled |
false | boolean | true | Boolean used to set the disabled attribute of the input(s) |
cardBrand |
false | string | true | String used to determine proper input format and default placeholder/aria-label |
placeholder |
false | string | true | String used to customize the placeholder attribute of the input |
aria-label |
false | string | true | String used to customize the aria-label attribute of the input |
onReady |
false | function | true | Event listener. See On Ready |
onChange |
false | function | true | Event listener. See On Change |
onFocus |
false | function | true | Event listener. See On Focus |
onBlur |
false | function | true | Event listener. See On Blur |
onKeyDown |
false | function | true | Event listener. See On Keydown |
BasisTheoryReact
BasisTheoryReact
adds React-specific capabilities on top of the BasisTheory
class. All API features and Tokenization Features are still available, plus the methods below.
getElement
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('test_1234567890', { elements: true });
const submit = async () => {
const fullName = bt.getElement('fullName');
const ssn = bt.getElement('ssn');
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" placeholder="Full name" aria-label="Full name" />
<TextElement id="ssn" placeholder="SSN" aria-label="Social Security Number" mask={ssnMask} transform={/[-]/} />
<div>
<button type="submit" onClick={submit} disabled={!bt}>Submit</button>
</div>
</BasisTheoryProvider>;
}
Typescript
import type {
CardExpirationDateElement as ICardExpirationDateElement
} from '@basis-theory/basis-theory-react/types';
bt.getElement('expDate').month(); // Error TS2551: property doesn't exist
(bt.getElement('expDate') as ICardExpirationDateElement).month(); // no error
bt.getElement<ICardExpirationDateElement>('expDate').month() // no error
Gets the underlying Element instance. Given the declarative nature of React, this method enables referencing the Element value for tokenization.
The targeted Element must be present in your component tree (virtual DOM) when invoking this method.
Parameter | Required | Type | Description |
---|---|---|---|
id |
true | string | The id of the Element instance |
You can type-cast getElement
method to safely call specific Elements methods.