Reputation: 43
I am opening two js files to import stripe function following the tutorial. My stripe payment will appear in a modal. How can I close the modal after I receive successful payment message in the child?
The codes are as follow: Parent (some codes are eliminated for easy reading)
<Modal isOpen={modalPurchase} toggle={togglePurchase}>
<Stripe/>
</Modal>
The Child:
import React, { useState } from 'react'
import { Elements } from "@stripe/react-stripe-js"
import { loadStripe } from '@stripe/stripe-js'
import "./Stripe.css"
import PaymentForm from './PaymentForm'
const PUBLIC_KEY = "pk_test_"
const stripeTestPromise = loadStripe(PUBLIC_KEY)
const sendPaymentFormToStripe = () => {
setPaymentSuccess(true)
}
export default function Stripe() {
return (
<Elements stripe={stripeTestPromise} >
<PaymentForm />
</Elements>
)
};
Child of Stripe:
import React, { useState } from 'react'
import { CardElement, useElements, useStripe } from "@stripe/react-stripe-js"
import * as axios from 'axios'
import { Button } from 'reactstrap'
import "./Stripe.css"
const CARD_OPTIONS = {
iconStyle: "solid",
style: {
base: {
iconColor: "#c4f0ff",
color:"fff",
fontWeight: 500,
fontSize: "16px",
fontSmoothing:"antialiased",
},
invaild: {
iconColor: "#ffc7ee",
color: "ffc7ee"
}
}
}
export default function PaymentForm() {
const [success, setSuccess] = useState(false)
const stripe = useStripe()
const elements = useElements()
const handleSubmit = async (e) => {
e.preventDefault()
const { error, paymentMethod } = await stripe.createPaymentMethod({
type: "card",
card: elements.getElement(CardElement)
})
if (!error) {
try {
const { id } = paymentMethod
const response = await axios.post('http://localhost:8080/checkout', {
amount: 500,
id
})
if (response.data.success) {
console.log('Successful payment')
setSuccess(true)
}
} catch (error) {
console.log('Error', error)
}
} else {
console.log(error.message)
}
}
return (
<div>
{!success ?
<form onSubmit={handleSubmit}>
<fieldset className="FormGroup">
<div className="FormRow">
<CardElement options={CARD_OPTIONS} />
</div>
</fieldset>
<Button>Pay</Button>
</form >
:
<div>
<h2>Successful</h2>
</div>
}
</div>
)
}
Upvotes: 0
Views: 50
Reputation: 11156
One way could be passing togglePurchase
function as props to Stripe
and PaymentForm
components. So your code becomes:
Parent:
<Modal isOpen={modalPurchase} toggle={togglePurchase}>
<Stripe toggle={togglePurchase}/>
</Modal>
Stripe:
...
export default function Stripe(props) {
return (
<Elements stripe={stripeTestPromise} >
<PaymentForm toggle={props.toggle}/>
</Elements>
)
};
PaymentForm:
...
export default function PaymentForm(props) {
...
const handleSubmit = async (e) => {
...
if (response.data.success) {
console.log('Successful payment')
setSuccess(true)
props.toggle() //<-- call toggle function
}
...
}
}
Upvotes: 2