@basis-theory/react-elements

中文文档
3.5.0发布于 2026/11/05Apache-2.0TypeScriptESM + CJS近 30 天下载 30.9万

React components for Basis Theory Elements v3

原始使用文档
文档目录16 节
  1. Installation
  2. Quick Start
  3. Components
  4. BasisTheoryProvider
  5. CardNumberElement
  6. ExpiryElement
  7. CVVElement
  8. TextElement
  9. CardElement
  10. Shared Element Props
  11. Hooks
  12. useBasisTheory
  13. Ref Methods
  14. TypeScript
  15. Documentation
  16. License

@basis-theory/react-elements

React components for collecting sensitive data with Basis Theory Elements v3. Secure, PCI-compliant iframes wrapped as React components with hooks, refs, and typed event handlers.

Installation

npm install @basis-theory/react-elements@beta

@basis-theory/web-elements is a dependency and will be installed automatically.

React 16.8+, 17, 18, and 19 are supported.

Quick Start

import { useState, useRef } from 'react';
import {
  BasisTheoryProvider,
  CardNumberElement,
  ExpiryElement,
  CVVElement,
  useBasisTheory,
} from '@basis-theory/react-elements';

function PaymentForm() {
  const { bt, error } = useBasisTheory();
  const cardNumberRef = useRef(null);
  const expiryRef = useRef(null);
  const cvvRef = useRef(null);

  const [cardNumberValid, setCardNumberValid] = useState(false);
  const [expiryValid, setExpiryValid] = useState(false);
  const [cvvValid, setCvvValid] = useState(false);

  const allValid = cardNumberValid && expiryValid && cvvValid;

  if (error) return <div>Failed to load payment form.</div>;

  const handleSubmit = async (e) => {
    e.preventDefault();

    const token = await bt.tokens.create({
      type: 'card',
      data: {
        number: cardNumberRef.current,
        expiration_month: expiryRef.current,
        expiration_year: expiryRef.current,
        cvc: cvvRef.current,
      },
    });

    // Send token.id to your backend
    console.log('Token created:', token.id);
  };

  return (
    <form onSubmit={handleSubmit}>
      <CardNumberElement
        ref={cardNumberRef}
        placeholder="4242 4242 4242 4242"
        onChange={(event) => setCardNumberValid(event.detail.isValid)}
      />
      <ExpiryElement
        ref={expiryRef}
        placeholder="MM/YY"
        onChange={(event) => setExpiryValid(event.detail.isValid)}
      />
      <CVVElement
        ref={cvvRef}
        placeholder="123"
        onChange={(event) => setCvvValid(event.detail.isValid)}
      />
      <button type="submit" disabled={!allValid}>Pay</button>
    </form>
  );
}

export default function App() {
  return (
    <BasisTheoryProvider apiKey="pk_test_...">
      <PaymentForm />
    </BasisTheoryProvider>
  );
}

Components

BasisTheoryProvider

Initializes the SDK and provides it to child components via React Context. All element components and the useBasisTheory hook must be descendants of this provider.

<BasisTheoryProvider
  apiKey="pk_test_..."
  options={{
    debug: true,
    themeMode: 'auto',
    theme: { /* ThemeTokens */ },
  }}
  errorFallback={<div>Something went wrong.</div>}
>
  {children}
</BasisTheoryProvider>
PropTypeRequiredDescription
apiKeystringYesPublic API key (starts with pk_)
optionsSDKOptionsNoSDK configuration (debug, theme, etc.)
childrenReactNodeYesChild components
errorFallbackReactNodeNoFallback UI if initialization fails

CardNumberElement

Secure card number input with Luhn validation and brand detection.

<CardNumberElement
  ref={cardNumberRef}
  placeholder="4242 4242 4242 4242"
  ariaLabel="Card number"
  disabled={false}
  readOnly={false}
  onChange={(event) => console.log(event.detail.isValid)}
  onReady={(event) => console.log('Ready')}
  onFocus={(event) => console.log('Focused')}
  onBlur={(event) => console.log('Blurred')}
  onError={(event) => console.error(event.detail.code)}
  className="my-card-input"
  containerStyle={{ border: '1px solid #ccc' }}
/>

ExpiryElement

Secure expiry date input (MM/YY format).

<ExpiryElement
  ref={expiryRef}
  placeholder="MM/YY"
  onChange={(event) => console.log(event.detail.isValid)}
/>

CVVElement

Secure CVV/CVC input. Automatically adjusts expected length when a CardNumberElement is present on the same page (3 digits for Visa/Mastercard, 4 for Amex).

<CVVElement
  ref={cvvRef}
  placeholder="123"
  onChange={(event) => console.log(event.detail.isValid)}
/>

TextElement

General-purpose secure text input for any sensitive value (SSN, account numbers, etc.).

<TextElement
  ref={textRef}
  placeholder="###-##-####"
  mask={[/\d/, /\d/, /\d/, '-', /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]}
  transform={[/-/g, '']}
  validation={/^\d{9}$/}
  password={false}
  inputMode="numeric"
  required={true}
  maxLength={11}
  onChange={(event) => console.log(event.detail.isValid)}
/>

CardElement

Unified card element that combines card number, expiry, and CVV into a single component.

<CardElement
  ref={cardRef}
  placeholder={{
    cardNumber: '4242 4242 4242 4242',
    expiryDate: 'MM/YY',
    cvc: '123',
  }}
  layout="auto"
  stackAt={400}
  iconPosition="right"
  onChange={(event) => console.log(event.detail.isValid)}
/>

Shared Element Props

All element components accept:

PropTypeDescription
placeholderstringPlaceholder text
disabledbooleanDisable the input
readOnlybooleanMake the input read-only
ariaLabelstringARIA label for accessibility
onReady(event) => voidFired when the element is interactive
onChange(event) => voidFired when the value changes
onFocus(event) => voidFired when the element gains focus
onBlur(event) => voidFired when the element loses focus
onError(event) => voidFired on infrastructure or API errors
classNamestringCSS class for the container div
containerStyleCSSPropertiesInline styles for the container div

Hooks

useBasisTheory

Access the SDK instance from any component under BasisTheoryProvider.

import { useBasisTheory } from '@basis-theory/react-elements';

function MyComponent() {
  const { bt, error } = useBasisTheory();

  if (error) return <div>SDK failed to initialize.</div>;
  if (!bt) return <div>Loading...</div>;

  const handleTokenize = async () => {
    const token = await bt.tokens.create({
      type: 'card',
      data: { number: cardNumberRef.current },
    });
  };
}

Returns { bt: BasisTheorySDK | null, error: Error | null }.

Ref Methods

All element refs expose these methods and properties:

Method / PropertyTypeDescription
mount(selector) => Promise<void>Mount the element (handled automatically)
unmount() => voidRemove the element
update(options) => Promise<void>Update element options
focus() => voidFocus the input
blur() => voidBlur the input
clear() => voidClear the input value
on(event, listener) => () => voidSubscribe to an event
completebooleanInput is valid and non-empty
emptybooleanInput is empty
validbooleanInput passes validation
idstringUnique element ID
typestringElement type
mountedbooleanWhether the element is mounted

CardNumberElementRef adds: cardBrand, last4, bin.

CardElementRef adds: cardBrand, last4, bin, errors, number, expiryDate, cvc.

TypeScript

All components are fully typed. Import ref types for useRef:

import { useRef } from 'react';
import type {
  CardNumberElementRef,
  CVVElementRef,
  ExpiryElementRef,
  TextElementRef,
  CardElementRef,
} from '@basis-theory/react-elements';

const cardNumberRef = useRef<CardNumberElementRef | null>(null);
const cvvRef = useRef<CVVElementRef | null>(null);
const expiryRef = useRef<ExpiryElementRef | null>(null);

Event handler types are also available:

import type {
  ChangeEventDetail,
  CardNumberChangeEventDetail,
  CardElementChangeEventDetail,
  ReadyEventDetail,
  ErrorEventDetail,
  FocusEventDetail,
} from '@basis-theory/react-elements';

Documentation

Full documentation: https://developers.basistheory.com/docs/sdks/web/web-elements/

License

Apache-2.0

版本与发布记录

@basis-theory/react-elements 共发布 81 个版本,首次发布于 2025/02/20;过去 12 个月发布了 34 个版本。

版本发布日期距今
3.5.0latest2026/11/053 天前
2.18.1legacy2026/11/053 天前
3.4.02026/11/044 天前
2.18.02026/11/044 天前
3.3.12026/10/2316 天前
3.3.02026/10/2217 天前

其他发布通道:beta → 3.0.0-beta.6,legacy → 2.18.1。

关于 @basis-theory/react-elements 的常见问题

@basis-theory/react-elements 是什么?

React components for Basis Theory Elements v3

如何安装 @basis-theory/react-elements?

在项目目录运行 npm install @basis-theory/react-elements,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0)、react-dom(^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@basis-theory/react-elements 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@basis-theory/react-elements 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@basis-theory/react-elements 可以商用吗?

@basis-theory/react-elements 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@basis-theory/react-elements 的下载量有多少?

根据 npm 官方下载统计,@basis-theory/react-elements 在 2026/10/08 – 2026/11/06 这 30 天内被下载 308,555 次,日均约 10,285 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@basis-theory/react-elements 还在维护吗?

最新版本 3.5.0 发布于 2026/11/05(3 天前);至今共发布 81 个版本,其中过去 12 个月发布了 34 个;首次发布于 2025/02/20。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。