How to add Stripe.js script to React component

I would like to create a payment form using Stripe as a payment provider.

The Stripe.js link describes how to create a form component using jQuery, including the external script on the page. How can I include it in my React component? What is the best way? At the moment, I have the following:

import React, { Component } from 'react'; class PaymentForm extends Component { constructor(props) { super(props); } componentDidMount() { Stripe.setPublishableKey('THE-PUBLIC-KEY'); } handleSubmit(e) { e.preventDefault(); Stripe.card.createToken(e.currentTarget, (status, response) => { console.log( status, response ); }); } render() { //THE PAYMENT FORM } } 

Note1: I would not want to use ReactScriptLoader as it is not actively updated.

Note2: Also seen dangerouslySetInnerHTML solution, which I do not think is good practice.

+5
source share
2 answers

Stripe has officially released the react-stripe-elements module with React components to help you add Stripe Elements to your React app.

+1
source

Despite having an NPM module for Stripe, they do not support it for client applications. You will need to add the stripe.js library using the script tag to the index.html page (or wherever you generate the HTML element that React will mount and import the React scripts):

 <script src="https://js.stripe.com/v3/"></script> 

This is the recommended method from the Stripe documentation. It will create a Stripe object in a global area where it will be available for your React code.

I would be very afraid to use the library for payments in any way, except for those supported by its developer - I think that you are right to avoid ReactScriptLoader and dangerouslySetInnerHtml for this purpose.

If you are using ESLint, you can specify the global top of your JSX file to stop the warning:

 /* global Stripe */ 
+1
source

Source: https://habr.com/ru/post/1259275/


All Articles