React Integration

React Integration

The @dropfi/xrpl-react package provides a seamless way to integrate DropFi Wallet into your React applications using React Context and Hooks.

Overview

This official React integration package simplifies the process of connecting to DropFi Wallet by providing:

  • Automatic provider initialization
  • React hooks for easy state management
  • Built-in event handling
  • TypeScript support
Xrpl-react Repository

Installation

Install the package using your preferred package manager:

bash
# npm npm install @dropfi/xrpl-react # yarn yarn add @dropfi/xrpl-react # pnpm pnpm add @dropfi/xrpl-react

Quick Start

1. Wrap Your App with XrplProvider

First, wrap your React application with the XrplProvider component:

tsx
import { XrplProvider } from '@dropfi/xrpl-react'; import { App } from './App'; export default function Root() { return ( <XrplProvider> <App /> </XrplProvider> ); }

2. Use the Hook in Your Components

Access wallet functionality using the useXrplReact hook:

tsx
import { useXrplReact } from '@dropfi/xrpl-react'; function WalletConnect() { const { address, isConnected, connect, disconnect } = useXrplReact(); if (isConnected) { return ( <div> <p>Connected: {address}</p> <button onClick={disconnect}>Disconnect</button> </div> ); } return ( <button onClick={connect}>Connect Wallet</button> ); }

Hook API Reference

The useXrplReact() hook returns an object with the following properties:

State Properties

Property Type Description
address string | undefined Currently connected wallet address
wallet string | undefined Wallet identifier
isConnected boolean Connection status
connectedAccounts string[] Array of all connected accounts
network string Current network (livenet/testnet/devnet)
isConnecting boolean Loading state during connection
error string | null Error message if any
initialized boolean Provider initialization status

Methods

connect()

ts
connect: () => Promise<string>

Initiates wallet connection and returns the connected address.

disconnect()

ts
disconnect: () => Promise<void>

Disconnects the wallet.

sendTransaction()

ts
sendTransaction: (tx: any) => Promise<any>

Sends a transaction through the wallet. See Transaction Signing for details.

signMessage()

ts
signMessage: (message: string) => Promise<{ signature: string }>

Signs a message with the connected wallet.

changeNetwork()

ts
changeNetwork: (network: string) => Promise<any>

Switches to a different network (livenet, testnet, or devnet).

Complete Example

Here's a comprehensive example showing common wallet operations:

tsx
import React from 'react'; import { XrplProvider, useXrplReact } from '@dropfi/xrpl-react'; function WalletDemo() { const { address, isConnected, isConnecting, network, error, connect, disconnect, sendTransaction, signMessage, changeNetwork } = useXrplReact(); const handleSendPayment = async () => { try { const result = await sendTransaction({ TransactionType: 'Payment', Destination: 'rN7n7otQDd6FczFgLdSqtcsAUxDkw6fzRH', Amount: '1000000' // 1 XRP in drops }); console.log('Transaction successful:', result); } catch (err) { console.error('Transaction failed:', err); } }; const handleSignMessage = async () => { try { const result = await signMessage('Hello from DropFi!'); console.log('Signature:', result.signature); } catch (err) { console.error('Signing failed:', err); } }; if (error) { return <div className="error">Error: {error}</div>; } if (isConnecting) { return <div>Connecting to wallet...</div>; } if (!isConnected) { return ( <button onClick={connect}> Connect DropFi Wallet </button> ); } return ( <div> <h3>Wallet Connected</h3> <p>Address: {address}</p> <p>Network: {network}</p> <div className="actions"> <button onClick={handleSendPayment}> Send 1 XRP </button> <button onClick={handleSignMessage}> Sign Message </button> <button onClick={() => changeNetwork('testnet')}> Switch to Testnet </button> <button onClick={disconnect}> Disconnect </button> </div> </div> ); } export default function App() { return ( <XrplProvider> <WalletDemo /> </XrplProvider> ); }

Event Handling

The provider automatically listens to these wallet events:

  • xrpl_selectedAddress : Fired when the active address changes
  • xrpl_connectedAccounts : Fired when connected accounts change
  • xrpl_selectedNetwork : Fired when the network changes
  • xrpl_disconnect : Fired when the wallet disconnects

These events are handled internally and update the hook's state automatically.

TypeScript Support

The package includes TypeScript definitions. Here's an example with proper typing:

tsx
import { useXrplReact } from '@dropfi/xrpl-react'; interface PaymentProps { destination: string; amount: string; } function PaymentComponent({ destination, amount }: PaymentProps) { const { sendTransaction, isConnected } = useXrplReact(); const sendPayment = async () => { if (!isConnected) return; const tx = { TransactionType: 'Payment' as const, Destination: destination, Amount: amount }; try { const result = await sendTransaction(tx); console.log('Success:', result); } catch (error) { console.error('Failed:', error); } }; return ( <button onClick={sendPayment} disabled={!isConnected}> Send Payment </button> ); }

Best Practices

1. Error Handling

Always wrap async operations in try-catch blocks:

tsx
const connectWallet = async () => { try { await connect(); } catch (error) { // Handle connection errors console.error('Failed to connect:', error); } };

2. Check Connection Status

Always verify connection before performing operations:

tsx
const { isConnected, sendTransaction } = useXrplReact(); const handleTransaction = async () => { if (!isConnected) { alert('Please connect your wallet first'); return; } // Proceed with transaction };

3. Loading States

Provide feedback during async operations:

tsx
const [isLoading, setIsLoading] = useState(false); const handleAction = async () => { setIsLoading(true); try { await someAsyncOperation(); } finally { setIsLoading(false); } };

Requirements

  • React 16.8+ (requires hooks support)
  • DropFi Wallet extension or mobile app installed
  • The package requires window.xrpl to be available

Troubleshooting

Wallet Not Found

If window.xrpl is undefined:

  • Ensure DropFi Wallet extension is installed and enabled
  • For mobile apps, ensure the WebView properly injects the provider
  • Check that your app is served over HTTPS in production

Connection Issues

If connection fails:

  • Check that the user has created a wallet
  • Verify the wallet is unlocked
  • Ensure your domain is not blocked in wallet settings

Transaction Failures

For transaction issues:

  • Verify the transaction format matches XRPL specifications
  • Check account balance and reserves
  • Ensure proper network selection (mainnet vs testnet)

Support

For issues specific to the React package:

For general DropFi Wallet support, see Additional Support .