Reputation: 1932
I want to create a token with ReactJS
and stripe, I implemented the formCard
:
export default class sForm extends React.Component {
handleSubmit = (ev) => {
ev.preventDefault();
if (this.props.stripe) {
this.props.stripe
.createToken()
.then((payload) => console.log('[token]', payload));
} else {
console.log('Form submitted before Stripe.js loaded.');
}
};
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>Card details</label>
<CardElement
/>
<button disabled={!this.props.stripe}>Pay</button>
</form>
);
}
}
and my Elements
const stripePromise = loadStripe('pk_test_IqIuWVA2XNYPVx03KrFUNxNB00hMZkyNQt');
<Elements stripe={stripePromise}>
<ElementsConsumer>
{({stripe, elements}) => (
<SForm stripe={stripe} elements={elements} />)}
</ElementsConsumer></Elements>
Upvotes: 0
Views: 3961
Reputation: 1
Just change these lines.
const card = elements.getElement(CardElement)
const { token, error } = await stripe.createToken(card)
Upvotes: 0
Reputation: 3240
As the error message implies, you have to provide a Stripe Element when creating the token [0]. Assuming you are using the new React library (@stripe/react-stripe-js), you would do this by importing the useElements
hook to get an elements instance, and then call the getElement
method. For example:
import { CardElement, useStripe, useElements } from "@stripe/react-stripe-js";
export const sForm = () => {
const stripe = useStripe();
const elements = useElements();
const handleSubmit = (ev) => {
ev.preventDefault();
const cardElement = elements.getElement("card");
stripe.createToken(cardElement)
.then((payload) => console.log('[token]', payload));
};
return (
<form onSubmit={handleSubmit}>
<label>Card details</label>
<CardElement />
<button disabled={!stripe}>Pay</button>
</form>
);
}
I've prepped a full working example that you can reference here:
https://codesandbox.io/s/demo-react-stripe-js-starting-point-h10v9
The relevant code is under components/CheckoutForm.jsx
.
I hope this helps!
Upvotes: 1