UNPKG

kirapay-merchant-sdk

Version:

KiraPay JavaScript SDK for payment integration

129 lines (114 loc) 3.3 kB
import React, { useState, useEffect, useRef } from 'react'; function DynamicImportExample() { const [price, setPrice] = useState(100); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); const buttonRef = useRef(null); const buttonInstance = useRef(null); // Dynamic import function const loadSDK = async () => { try { const { ButtonDynamicPrice } = await import('kirapay-merchant-sdk'); return ButtonDynamicPrice; } catch (err) { throw new Error('Failed to load KiraPay SDK'); } }; // Initialize button const initializeButton = async () => { setIsLoading(true); setError(null); try { const ButtonDynamicPrice = await loadSDK(); // Create button instance buttonInstance.current = new ButtonDynamicPrice({ price: price, apiKey: "kp_dd152040d453075008309034a5846af1cf22616358b9eee1cf678c16316fe97c", title: `Pay $${price}`, customOrderId: `ORDER_${Date.now()}`, style: { backgroundColor: "#28a745", color: "white", padding: "12px 24px", borderRadius: "8px", border: "none", cursor: "pointer" } }); // Render button if (buttonRef.current) { buttonRef.current.appendChild(buttonInstance.current.render()); } } catch (err) { setError(err.message); } finally { setIsLoading(false); } }; // Handle price change const handlePriceChange = (e) => { const newPrice = +e.target.value; setPrice(newPrice); if (buttonInstance.current) { buttonInstance.current.updatePrice(newPrice); } }; // Cleanup on unmount useEffect(() => { return () => { if (buttonInstance.current) { buttonInstance.current.destroy(); } }; }, []); return ( <div style={{ padding: '20px' }}> <h2>Dynamic Import Example</h2> <p>SDK is loaded only when needed, reducing initial bundle size.</p> <div style={{ marginBottom: '20px' }}> <label htmlFor="price">Amount: </label> <input type="number" id="price" value={price} onChange={handlePriceChange} style={{ padding: '8px', marginLeft: '10px', borderRadius: '4px', border: '1px solid #ddd' }} /> </div> <div style={{ marginBottom: '20px' }}> <button onClick={initializeButton} disabled={isLoading} style={{ padding: '8px 16px', backgroundColor: isLoading ? '#ccc' : '#007bff', color: 'white', border: 'none', borderRadius: '4px', cursor: isLoading ? 'not-allowed' : 'pointer' }} > {isLoading ? 'Loading SDK...' : 'Load SDK & Show Button'} </button> </div> {error && ( <div style={{ color: 'red', marginBottom: '20px', padding: '10px', backgroundColor: '#ffe6e6', borderRadius: '4px' }}> Error: {error} </div> )} <div ref={buttonRef}></div> </div> ); } export default DynamicImportExample;