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