After I get a token, I'd like to reset the Element fields, making it ready to add another card. in Stripe docs, there is an element.clear method(https://stripe.com/docs/stripe.js#other-methods), can I use it here, if yes, how to use it?
Yep! Because React components are declarative, you'll need to get a reference to the Element instance (called "refs" in React) in order to clear it.
<CardElement elementRef={(c) => this._element = c} />
and then in your handler where you want to clear the Element:
handleSubmit = (ev) => {
ev.preventDefault();
this.props.stripe.createToken();
// Clear the Element:
this._element.clear();
}
Closing this out, but let me know if that doesn't work for you!
That works, thanks!
elementRef seems deprecated in #181 and removed in #210
Using onReady instead of elementRef works fine.
How would you achieve this using React Hooks?
How would you achieve this using React Hooks?
I got it to work by using useState and not useRef
function SomeComponent() {
const [ ref, setRef ] = useState(null)
function someEvent() {
ref.clear()
}
return (
<CardElement
onReady={e => setRef(e)}
/>
)
}
I think the best way to clear the contents is to use Stripe's "useElements" hook
import {useStripe, useElements, CardElement} from '@stripe/react-stripe-js'
function MyComponent() {
const stripe = useString();
const elements = useElements();
const handleSubmit = async (e) => {
...
const cardElement = elements.getElement(CardElement);
...
//Clear the contents of the CardElement
cardElement.clear()
...
}
return (
<CardElement />
)
}
const handleSubmit = (e) => {
elements.getElement(CardElement).clear();
//Or, If you are using the Split payment form you have to clear each element individually.
elements.getElement(CardNumberElement).clear();
elements.getElement(CardExpiryElement).clear();
elements.getElement(CardCvcElement).clear();
}
Most helpful comment
elementRefseems deprecated in #181 and removed in #210Using
onReadyinstead ofelementRefworks fine.