|
| 1 | +import React, { useState } from "react"; |
| 2 | +import { FormGroup, FormControl, ControlLabel } from "react-bootstrap"; |
| 3 | +import { CardElement, injectStripe } from "react-stripe-elements"; |
| 4 | +import LoaderButton from "./LoaderButton"; |
| 5 | +import { useFormFields } from "../libs/hooksLib"; |
| 6 | +import "./BillingForm.css"; |
| 7 | + |
| 8 | +function BillingForm({ isLoading, onSubmit, ...props }) { |
| 9 | + const [fields, handleFieldChange] = useFormFields({ |
| 10 | + name: "", |
| 11 | + storage: "" |
| 12 | + }); |
| 13 | + const [isProcessing, setIsProcessing] = useState(false); |
| 14 | + const [isCardComplete, setIsCardComplete] = useState(false); |
| 15 | + |
| 16 | + isLoading = isProcessing || isLoading; |
| 17 | + |
| 18 | + function validateForm() { |
| 19 | + return ( |
| 20 | + fields.name !== "" && |
| 21 | + fields.storage !== "" && |
| 22 | + isCardComplete |
| 23 | + ); |
| 24 | + } |
| 25 | + |
| 26 | + async function handleSubmitClick(event) { |
| 27 | + event.preventDefault(); |
| 28 | + |
| 29 | + setIsProcessing(true); |
| 30 | + |
| 31 | + const { token, error } = await props.stripe.createToken({ name: fields.name }); |
| 32 | + |
| 33 | + setIsProcessing(false); |
| 34 | + |
| 35 | + onSubmit(fields.storage, { token, error }); |
| 36 | + } |
| 37 | + |
| 38 | + return ( |
| 39 | + <form className="BillingForm" onSubmit={handleSubmitClick}> |
| 40 | + <FormGroup bsSize="large" controlId="storage"> |
| 41 | + <ControlLabel>Storage</ControlLabel> |
| 42 | + <FormControl |
| 43 | + min="0" |
| 44 | + type="number" |
| 45 | + value={fields.storage} |
| 46 | + onChange={handleFieldChange} |
| 47 | + placeholder="Number of notes to store" |
| 48 | + /> |
| 49 | + </FormGroup> |
| 50 | + <hr /> |
| 51 | + <FormGroup bsSize="large" controlId="name"> |
| 52 | + <ControlLabel>Cardholder's name</ControlLabel> |
| 53 | + <FormControl |
| 54 | + type="text" |
| 55 | + value={fields.name} |
| 56 | + onChange={handleFieldChange} |
| 57 | + placeholder="Name on the card" |
| 58 | + /> |
| 59 | + </FormGroup> |
| 60 | + <ControlLabel>Credit Card Info</ControlLabel> |
| 61 | + <CardElement |
| 62 | + className="card-field" |
| 63 | + onChange={e => setIsCardComplete(e.complete)} |
| 64 | + style={{ |
| 65 | + base: { fontSize: "18px", fontFamily: '"Open Sans", sans-serif' } |
| 66 | + }} |
| 67 | + /> |
| 68 | + <LoaderButton |
| 69 | + block |
| 70 | + type="submit" |
| 71 | + bsSize="large" |
| 72 | + isLoading={isLoading} |
| 73 | + disabled={!validateForm()} |
| 74 | + > |
| 75 | + Purchase |
| 76 | + </LoaderButton> |
| 77 | + </form> |
| 78 | + ); |
| 79 | +} |
| 80 | + |
| 81 | +export default injectStripe(BillingForm); |
0 commit comments