Search code examples
javascriptreactjspaypalfrontendpaypal-sandbox

Paypal dynamic value in react js


I need help with my project I want to add a dynamic option to the PayPal payment process. ( change the value to be dynamic )

the default option is value: '0.01' and the dynamic payment in my project is cart.subtotal.formatted_with_symbol

I try to add [const {amount} = cart.subtotal.formatted_with_symbol;] this line to try to change the value to value: amount but this is not working for me.

thanks for help

import React from 'react'
import ReactDOM from "react-dom"
import CartItem from './CartItem';

const PayPalButton = window.paypal.Buttons.driver("react", { React, ReactDOM });

// paypal payment buttons
    const createOrder = (data, actions) => {
        const {amount} = cart.subtotal.formatted_with_symbol;
        return actions.order.create({
          purchase_units: [
            {
              amount: {
                  value: amount,
              },
            },
          ],
        });
      }

      const onApprove = (data, actions) => {
        return actions.order.capture();
      }
      
onst FilledCart = () => (
        <>
            <div>
                {cart.line_items.map((item) => (
                    <div key={item.id}>
                        <CartItem item={item} handleUpdateCratQty={handleUpdateCratQty} handleRemoveFromCart={handleRemoveFromCart} />
                    </div>
                ))}
            </div>
            <div>
                <div>
                    <button onClick={handleEmptyCart}>EmptyCart</button>
                </div>
            </div>
        </>
    );

Solution

  • The react-paypal-js documentation is straightforward enough...

    import { useEffect } from "react";
    import {
        PayPalScriptProvider,
        PayPalButtons,
        usePayPalScriptReducer
    } from "@paypal/react-paypal-js";
    
    // This values are the props in the UI
    const amount = "2";
    const currency = "USD";
    const style = {"layout":"vertical"};
    
    // Custom component to wrap the PayPalButtons and handle currency changes
    const ButtonWrapper = ({ currency, showSpinner }) => {
        // usePayPalScriptReducer can be use only inside children of PayPalScriptProviders
        // This is the main reason to wrap the PayPalButtons in a new component
        const [{ options, isPending }, dispatch] = usePayPalScriptReducer();
    
        useEffect(() => {
            dispatch({
                type: "resetOptions",
                value: {
                    ...options,
                    currency: currency,
                },
            });
        }, [currency, showSpinner]);