EN
React - use PayPal donate button
10
points
In this short article, we would like to show how to use PayPal donate button in React.
Hint: to use PayPal donate button you need to have business account (business account creation is for free)
It is necessary to do few steps:
- Register donate button in PayPal panel (check this link),
- Integrate below source code with your site:
- add
https://www.paypalobjects.com/donate/sdk/donate-sdk.js
script at the end of your tempalte, - update
DonateButton
useEffect
source code using generated source code in PayPal panel or just copyhosted_button_id: 'PUT_YOUR_BUTTON_ID_HERE'
.
- add
Source code
template.html
file:
<!doctype html>
<html>
<head>
<!-- Site head elements here... -->
</head>
<body>
<!-- React root element here ... -->
<script src="https://www.paypalobjects.com/donate/sdk/donate-sdk.js" charset="UTF-8"></script>
</body>
</html>
DonateButton.jsx
file:
import React, { useEffect, useMemo } from 'react';
let counter = 0;
const generateId = () => {
return `ID-${++counter}`; // if it is necessary, use some better unique id generator
};
const DonateButton = () => {
const buttonRef = useRef(null);
const buttonId = useMemo(() => `ID-${generateId()}`, []);
useEffect(() => {
const button = window.PayPal.Donation.Button({
env: 'production',
hosted_button_id: 'PUT_YOUR_BUTTON_ID_HERE',
image: {
src: 'https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif',
alt: 'Donate with PayPal button',
title: 'PayPal - The safer, easier way to pay online!',
}
});
button.render(`#${buttonRef.current.id}`); // you can change the code and run it when DOM is ready
}, []);
return (
<div ref={buttonRef} id={buttonId} />
);
};
export default DonateButton;
Hint: change
PUT_YOUR_BUTTON_ID_HERE
value to id available in your PayPal panel.
Usage example:
import React from 'react';
import DonateButton from './DonateButton';
const App = () => {
return (
<div>
<DonateButton />
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);