Created
September 12, 2018 18:10
-
-
Save alexanmtz/cb66d307b67c78d35e855537c139b7b9 to your computer and use it in GitHub Desktop.
A example of a simple CheckoutForm with React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react' | |
import PropTypes from 'prop-types' | |
import { injectStripe } from 'react-stripe-elements' | |
class CheckoutForm extends Component { | |
constructor (props) { | |
super(props) | |
this.handleSubmit = this.handleSubmit.bind(this) | |
this.onChange = this.onChange.bind(this) | |
this.state = { | |
email: null, | |
fullname: null, | |
authenticated: false, | |
userId: null, | |
error: { | |
fullname: false, | |
email: false, | |
payment: false, | |
message: 'loading' | |
}, | |
paymentRequested: false | |
} | |
} | |
handleSubmit (ev) { | |
this.props.stripe | |
.createToken({ name: this.state.fullname }) | |
.then(({ token }) => { | |
// do something with the token | |
}) | |
.catch(e => { | |
// eslint-disable-next-line no-console | |
console.log('error to create token') | |
// eslint-disable-next-line no-console | |
console.log(e) | |
this.props.addNotification('Erro no pagamento') | |
this.setState({ | |
paymentRequested: false | |
}) | |
}) | |
// However, this line of code will do the same thing: | |
// this.props.stripe.createToken({type: 'card', name: 'Jenny Rosen'}); | |
} | |
onChange (ev) { | |
ev.preventDefault() | |
let formData = {} | |
formData[ev.target.name] = ev.target.value | |
this.setState(formData) | |
this.setState({ paymentRequested: false }) | |
} | |
componentDidMount () { | |
const { user } = this.props | |
if (user && user.id) { | |
this.setState({ | |
authenticated: true, | |
fullname: user.name, | |
email: user.email, | |
userId: user.id | |
}) | |
} | |
} | |
render () { | |
const logged = this.state.authenticated | |
const { user } = this.props | |
return ( | |
<form | |
onSubmit={ this.handleSubmit } | |
onChange={ this.onChange } | |
style={ { marginTop: 20 } } | |
></form> | |
) | |
} | |
} | |
CheckoutForm.propTypes = { | |
stripe: PropTypes.object, | |
onPayment: PropTypes.func, | |
task: PropTypes.any, | |
onClose: PropTypes.func, | |
addNotification: PropTypes.func, | |
itemPrice: PropTypes.any, | |
user: PropTypes.object | |
} | |
export const CheckoutFormPure = CheckoutForm | |
export default injectStripe(CheckoutForm) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment