Stripe Elements <> React
by Michelle Bu
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
<script src="https://npmcdn.com/react@latest/dist/react-with-addons.js"></script>
<script src="https://npmcdn.com/react-dom@latest/dist/react-dom.js"></script>
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>
<script src="https://js.stripe.com/v3/"></script>
<h1>
Please use <a href="https://github.com/stripe/react-stripe-elements">react-stripe-elements.</a>
</h1>
<hr>
<div id="checkout-mount">
<!-- This element's contents will be replaced with your component. -->
</div>
<div id="checkout-toggle">
<!-- This element's contents will be replaced with your component. -->
</div>
CSS
html {
font-family: sans-serif;
}
#checkout-mount, #checkout-toggle {
padding: 20px;
border: 1px solid #ccc;
margin: 20px 0;
}
JavaScript 1.7
class CheckoutMount extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
this._cardField = this.props.elements.create('card');
this._cardField.mount('#card-element-mount');
}
handleSubmit(ev) {
ev.preventDefault();
this.props.stripe.createToken(this._cardField).then(({token}) => this.setState({token}));
}
render() {
return (
<div>
<em>This example shows a component that always renders the subtree containing the Stripe Element.</em>
<form onSubmit={this.handleSubmit.bind(this)}>
<div id="card-element-mount" />
<button>Pay</button>
</form>
<div>
{this.state.token && `Token: ${this.state.token.id}`}
</div>
</div>
);
}
}
class CheckoutToggle extends React.Component {
constructor(props) {
super(props);
this.state = {
showCardElement: false,
};
}
handleSubmit(ev) {
ev.preventDefault();
this.props.stripe.createToken(this._cardField).then(({token}) => this.setState({token}));
}
handleToggle() {
this.setState({showCardElement: !this.state.showCardElement});
}
handleRef(elementWrapper) {
if (elementWrapper) {
this._cardField = this._cardField || this.props.elements.create('card');
this._cardField.mount('#card-element-toggle');
} else {
this._cardField.unmount();
}
}
render() {
return (
<div>
<em>This example shows a component that conditionally renders the subtree containing the Stripe Element.</em>
<form onSubmit={this.handleSubmit.bind(this)}>
<button type="button" onClick={this.handleToggle.bind(this)}>
{this.state.showCardElement ? 'Hide' : 'Show'}
</button>
{this.state.showCardElement && <div id="card-element-toggle" ref={this.handleRef.bind(this)} />}
{this.state.showCardElement && <button>Pay</button>}
</form>
<div>
...