I am trying to add paypal button using React.
According to paypals dev guide i need to include
<script src="https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID"></script>
in <head></head>
in index.html
tag and then use
import React from "react";
import ReactDOM from "react-dom"
const PayPalButton = paypal.Buttons.driver("react", { React, ReactDOM });
function YourComponent() {
const createOrder = (data, actions) => {
return actions.order.create({
purchase_units: [
{
amount: {
value: "0.01",
},
},
],
});
};
const onApprove = (data, actions) => {
return actions.order.capture();
};
return (
<PayPalButton
createOrder={(data, actions) => createOrder(data, actions)}
onApprove={(data, actions) => onApprove(data, actions)}
/>
);
}
However
const PayPalButton = paypal.Buttons.driver("react", {React, ReactDOM});
line throws error
'paypal' is not defined no-undef
It the object included from external <script>
isn't loaded. How can i load load object from external <script>
into React component then?
CodePudding user response:
There are two ways to square that circle:
const PayPalButton = window.paypal.Buttons.driver("react", { React, ReactDOM });
Remember that in Javascript global variables are also properties of the global object (window
in the browser). I actually like doing this for globals, because it makes it very clear in the code that this thing is a global variable rather than reading it and going "WTF where did that come from?".
You can also (assuming ESLint) suppress the lint warning directly (NOT recommended):
// eslint-disable-line no-undef
const PayPalButton = paypal.Buttons.driver("react", { React, ReactDOM });