React.js ライブラリ「react-payment-inputs」を使用してクレジットカードの入力フォームを実装する

React.js ライブラリ「react-payment-inputs」を使用してクレジットカードの入力フォームを実装する

ライブラリ「react-payment-inputs」をインストールすると、クレジットカードの入力フォームの簡単かつ高機能なもの実装可能がです。ここでは、react.jsでreact-payment-inputsを利用するための手順と簡単な使い方を記述してます。

環境

  • OS  CentOS Linux release 8.0.1905 (Core)
  • node V12.13.1
  • npm 6.14.1
  • React 16.13.0

react.js環境構築

下記のコマンドで構築してます。ここでは、react-appという名前でプロジェクトを作成してます。

create-react-app react-app

react-payment-inputsインストール

作成したプロジェクトに移動して、インストールします。

## 作成したプロジェクトに移動
cd react-app
 
## インストール
npm install react-payment-inputs styled-components

ここではstyled-componentsも利用します。

react-payment-inputs使い方

srcディレクトリにsample.jsと名前で下記のコードを記述します。

import React from 'react';
import { PaymentInputsWrapper, usePaymentInputs } from 'react-payment-inputs';
import images from 'react-payment-inputs/images';

export const Sample = () => {
    const {
        wrapperProps,
        getCardImageProps,
        getCardNumberProps,
        getExpiryDateProps,
        getCVCProps
      } = usePaymentInputs();    

    return (
        <PaymentInputsWrapper {...wrapperProps}>
            <svg {...getCardImageProps({ images })} />
            <input {...getCardNumberProps()} />
            <input {...getExpiryDateProps()} />
            <input {...getCVCProps()} />
        </PaymentInputsWrapper>
    )
}
  
export default Sample

次に、srcディレクトリ配下にあるApp.jsを下記のように編集します。

import React from 'react';
import Sample from './sample';
import './App.css';

function App() {
  const style = {
    width: "50%",
    margin: "0 auto",
    marginTop: 150
  };
  return (
    <div className="App">
      <div style={style}>
        <Sample />
      </div>
    </div>
  );
}

export default App;

実行します。

npm start

ブラウザから http://プライベートIP:3000にアクセスすると、高機能なクレジットカードの入力フォームが実装されていることが確認できます。