React-stripe-elements: How to reset/clear the Element

Created on 11 Jul 2017  路  8Comments  路  Source: stripe/react-stripe-elements

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?

Most helpful comment

elementRef seems deprecated in #181 and removed in #210

Using onReady instead of elementRef works fine.

All 8 comments

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();

}

Was this page helpful?
0 / 5 - 0 ratings

Related issues

shortcircuit3 picture shortcircuit3  路  5Comments

kongakong picture kongakong  路  4Comments

mmmikeal picture mmmikeal  路  4Comments

max-favilli picture max-favilli  路  5Comments

michael811 picture michael811  路  5Comments