How to prevent rendering multiple PayPal buttons in react

32 Views Asked by At

I'm trying to integrate PayPal buttons in my react web app but I keep getting duplicated buttons, with many messages in my console which show that there is something causing them to render multiple times. This is the code:


import React,{useCallback, useEffect, useRef, useState} from 'react'
import { PayPalScriptProvider, PayPalButtons } from "@paypal/react-paypal-js";
import Navbar from '../../Compononets/Navbar/Navbar'
import Footer from '../../Compononets/Fotter/Fotter'
import './Pricing.scss'
export default function Pricing() {
    
  useEffect(()=>{
    {
      window.paypal.Buttons({
       style: {
         shape: 'rect',
         color: 'gold',
         layout: 'vertical',
         label: 'subscribe'
       },
       createSubscription: (data, actions)=> {
         return actions.subscription.create({
           plan_id: 'P-80J548859J6351349MXTUSOY'
         });
       },
       onApprove: (data, actions)=> {
         alert(data.subscriptionID); // Optional success message
       }
     }).render('#paypal-button-container')
     }
  },[])
     
      return (
        <>
          <Navbar />
          <h1>This is pricing</h1>
          
          <div className="App">
          <div id="paypal-button-container"></div>
          </div>
         
          <Footer />
        </>
      );
      
    
}
1

There are 1 best solutions below

2
Adam Jenkins On

It's likely because you're running in StrictMode which runs effects twice to find logical errors when effects aren't cleaned up correctly. It found one.

I'd recommend a different solution - use a callback ref:

<div id="paypal-button-container" ref={useCallback(el => {
  if(!el) return; 
  
  // all the code from your useEffect
 
},[]}></div>