Stripe custom form with Reactjs

- 1 answer

Ad

While creating custom form, on submission you are required to send the form to the server. This is quite simple with DOM selectors. Here:

var $form = $('#payment-form');
Stripe.createToken($form, this.stripe_response_handler);

However one should not directly try to modify or access DOM when using React. To overcome this, I used ref. Here:

<Form onSubmit={this.select_plan} ref={(ref) => this.paymentForm = ref} >
...
</Form>

and then

Stripe.createToken(this.paymentForm, this.stripe_response_handler);

However this resulted in error:

Uncaught TypeError: Converting circular structure to JSON

What is the correct way of doing this in React?

Ad

Answer

Ad

There are several ways how you can use Stripe.js, you can pass form DOMElement (and you don't need use ref, because you can get form element from e.target in onSubmit event) where there are data attributes for Stripe

var StripeComponent = React.createClass({
  componentDidMount: function () {
    Stripe.setPublishableKey(); // set your test public key
  },

  handleSubmit: function (e) {
    e.preventDefault();
    Stripe.card.createToken(e.currentTarget, function (status, response) {
      console.log( status, response );      
    });
  },

  render: function() {
    return <form method="post" onSubmit={ this.handleSubmit }>
      <input size="20" data-stripe="number" placeholder="number"/>
      <input size="4" data-stripe="cvc" placeholder="cvc" />
      <input size="2" data-stripe="exp-month" placeholder="exp-month" />
      <input size="4" data-stripe="exp-year" placeholder="exp-year" />
      <button type="submit">Pay</button>
    </form>;
  }
});

Example

or you can create custom data object like this

var StripeComponent = React.createClass({
  getInitialState: function () {
    return {
      card: {
        number: '',
        cvc: '',
        exp_month: '',
        exp_year: ''
      }
    }
  },

  componentDidMount: function () {
    Stripe.setPublishableKey(); // set your test public key
  },

  handleSubmit: function (e) {
    e.preventDefault();
    Stripe.createToken(this.state.card, function (status, response) {
      console.log( status, response );
    });
  },

  handleChange: function (e) {
    let card = this.state.card;
    card[e.target.name] = e.target.value
    this.setState(card);
  },

  render: function() {
    return <form onSubmit={ this.handleSubmit }>
      <input size="20" name="number" onChange={this.handleChange} />
      <input size="4" name="cvc" onChange={this.handleChange} />
      <input size="2" name="exp_month" onChange={this.handleChange} />
      <input size="4" name="exp_year" onChange={this.handleChange} />
      <button type="submit">Pay</button>
    </form>
  }
});

Example

Note - To test examples you need set public key

Ad
source: stackoverflow.com
Ad