28
26

More than 5 years have passed since last update.

Reactで外部Scriptを動的に読み込む

Posted at

外部scriptを画面遷移するたびに読み込みたい・・・

Webpayが提供しているCheckoutHelperを使うと、数行コピペするだけでCredit決済に必要なクライアント側の機能が実装できます。
参考 : http://engineering.webpay.co.jp/2014/08/26/checkout-helper-usage/
外部Scriptを読み込むことでwebpay仕様のボタン&入力フォームを表示する方式なのですが、renderの中にそのまま書いてもscriptがloadされないので表示されませんでした。

scriptタグをrenderの中に書いてもボタンが表示されてくれない・・・

render() {
  return (
    <div className="payment jumbotron center-block">
      <h1>Payment</h1>
      <form action="/purchase" method="post">
      <script src="https://checkout.webpay.jp/v2/" className="webpay-button" data-key="test_public_bMj6ai5NZbYSbNraz51jkf7j" data-lang="ja"></script>
      </form>
    </div>
  );
}

appendChildでscriptタグを挿入

一応componentDidMountでappendChild、componentWillUnmountでremoveChildすれば表示されるようになりました。
ただ、Reactを通さないDOM操作をするとReactのstate変化で再描画するときに消えてしまったりするのでベストのやり方ではないような・・・。
良い方法あったら教えて下さいm(__)m

import React from 'react';

export default class Payment extends React.Component {

  componentDidMount() {
    var webpayForm = React.findDOMNode(this.refs.webpayForm);
    var script = document.createElement("script");
    script.setAttribute("src","https://checkout.webpay.jp/v2/");
    script.setAttribute("class","webpay-button");
    script.setAttribute("data-key", "test_public_19DdUs78k2lV8PO8ZCaYX3JT");
    script.setAttribute("data-lang", "ja");
    script.setAttribute("data-token-name", "webpayToken");
    script.setAttribute("id", "webpayButton");
    webpayForm.appendChild(script);
  }

  componentWillUnmount() {
    var webpayForm = React.findDOMNode(this.refs.webpayForm);
    webpayForm.removeChild(document.getElementById("webpayButton"));
    //for preventing webpay error
    window.WebPay = void(0);
    window.WebPayCheckoutHelper = void(0);
  }

  render() {
    return (
      <div className="payment jumbotron center-block">
        <h1>Payment</h1>
        <form action="/purchase" method="post" role="form" ref="webpayForm">
        </form>
      </div>
    );
  }
}

CheckoutHelperをSingle page applicationで使うのは辛い・・・

WebpayのCheckoutHelperはSingle page applicationで実装されることを想定されていなくていろいろと辛いです。
再読み込みをすると1度しか読み込みできないというWebpayの仕様にひっかかってしまいます。
こんなエラーがでます。
window.WebPay is already defined. Loading twice?
WebPay CheckoutHelper is already initialized. You cannot place two helpers per page.

componentWillUnmountで以下のようなcodeを入れると回避できるのですが、この対応で問題がないのかあるのかは分かりません。。
window.WebPay = void(0);
window.WebPayCheckoutHelper = void(0);

Single page applicationでwebpay使うときはCheckoutHelper使わない方がいいのかも・・・。

28
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
26