In react, setting up on('change') handler for stripe cardElement, issue with null values

Viewed 28

We are attempting to use the cardElement.on('change') functionality in our react application. We have the following:

function OurApp = () => {

    const stripe = useStripe();
    let cardElement = elements.getElement('card');
    // let cardElement = elements ? elements.getElement('card') : null;
    cardElement.on('change', (event) => {
        // do something on change
    });

    return (
        <CardElement
            options={cardElementOpts}
        />
    )
}

When we run the code above, we receive the error TypeError: Cannot read properties of null (reading 'getElement') because stripe === null on the first rendering. If we replace the let cardElement = line with elements ? elements.getElement('card') : null;, we receive the error Cannot read properties of null (reading 'on') because cardElement === null and null has no .on.

How can we properly setup the on('change') here?

update: useEffect that doesn't seem close to working. I need to check for non null for both elements and carddElement

let cardCheck = elements ? elements.getElement('card') : null;
useEffect(() => {
    if (elements) {
        let carddElement = elements.getElement('card');
        if (carddElement) {
            cardCheck.on('change', (event) => {
                console.log('event: ', event);
            });
        }
    }
}, [elements, cardCheck]);
1 Answers

Stripe's Elements have an onChange property[1] that allows you to pass in the function to handle any changes to the element. When your handler is called, an event object will be passed in that includes non-sensitive information on what has changed within the element (the stripe.js reference doc lays out what info you will get in this event[2]).

const handleChange = (event) => {
  console.log('[change]:', event);
};

function OurApp = () => {

    const stripe = useStripe();
    let cardElement = elements.getElement('card');
    // let cardElement = elements ? elements.getElement('card') : null;
    cardElement.on('change', (event) => {
        // do something on change
    });

    return (
        <CardElement
            onChange={handleChange}
        />
    )
}

[1] https://stripe.com/docs/stripe-js/react#element-components:~:text=Element%20loses%20focus.-,onChange,-optional%20(event%3A%20Object

[2] https://stripe.com/docs/js/element/events/on_change?type=cardElement#element_on_change-handler

Related