Languages
[Edit]
EN

React - use PayPal donate button

10 points
Created by:
troya
692

In this short article, we would like to show how to use PayPal donate button in React.

Example PayPal donate button in React.
Example 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:

  1. Register donate button in PayPal panel (check this link),
  2. 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 copy hosted_button_id: 'PUT_YOUR_BUTTON_ID_HERE'.

 

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

 

References

  1. Add the Buttons - Homepage

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join