SCALE — Build Lab
UI部品 · REACT COMPONENT

カード入力フォーム(Stripe Elements)

CATEGORYUI部品 TYPEReact Component EFFORT60〜120分 DIFFICULTY
PRIMARY CODE
tsx
'use client';
import { CardElement, useStripe, useElements } from '@stripe/react-stripe-js';

export function CardInputForm({ onSuccess }: { onSuccess: (pmId: string) => void }) {
  const stripe = useStripe();
  const elements = useElements();

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!stripe || !elements) return;
    const card = elements.getElement(CardElement)!;
    const { error, paymentMethod } = await stripe.createPaymentMethod({ type: 'card', card });
    if (error) alert(error.message);
    else onSuccess(paymentMethod.id);
  }

  return (
    <form onSubmit={handleSubmit}>
      <CardElement options={{ style: { base: { fontSize: '16px', color: '#fff' } } }} />
      <button type="submit" disabled={!stripe}>登録</button>
    </form>
  );
}
DEPENDENCIES
@stripe/stripe-js@stripe/react-stripe-js
前提条件
Tailwind CSS v4TypeScript 5
USE CASES
  • 任意のダッシュボードに組み込み

カード入力フォーム(Stripe Elements)

:LiTarget: 用途

Stripe Elements を使ったクレカ入力。PCI DSS準拠。

:LiSparkle: 特徴

  • Stripe Elements
  • リアルタイムバリデーション
  • ブランドアイコン自動表示
  • エラーメッセージ

:LiCode: コード(コピペ用)

'use client';
import { CardElement, useStripe, useElements } from '@stripe/react-stripe-js';

export function CardInputForm({ onSuccess }: { onSuccess: (pmId: string) => void }) {
  const stripe = useStripe();
  const elements = useElements();

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!stripe || !elements) return;
    const card = elements.getElement(CardElement)!;
    const { error, paymentMethod } = await stripe.createPaymentMethod({ type: 'card', card });
    if (error) alert(error.message);
    else onSuccess(paymentMethod.id);
  }

  return (
    <form onSubmit={handleSubmit}>
      <CardElement options={{ style: { base: { fontSize: '16px', color: '#fff' } } }} />
      <button type="submit" disabled={!stripe}>登録</button>
    </form>
  );
}

:LiHandPointer: 使い方

対象プロジェクトに該当ファイルをコピーして、props を流し込むだけ。

:LiAlertCircle: 注意事項

  • 依存パッケージを忘れず追加