### Install snaptrade-react Source: https://github.com/passiv/snaptrade-react/blob/main/README.md Install the snaptrade-react package using npm. ```shell npm install snaptrade-react ``` -------------------------------- ### Implement Custom Connection UI with useWindowMessage Hook Source: https://context7.com/passiv/snaptrade-react/llms.txt Use this hook to listen for postMessage events from the SnapTrade iframe. It automatically handles messages from allowed SnapTrade origins. ```tsx import { useEffect, useState } from 'react'; import { useWindowMessage } from 'snaptrade-react/hooks/useWindowMessage'; const CustomConnectionPortal = () => { const [connectionStatus, setConnectionStatus] = useState<'idle' | 'connecting' | 'success' | 'error'>('idle'); const [authId, setAuthId] = useState(null); const [errorDetails, setErrorDetails] = useState(null); const handleSuccess = (authorizationId: string) => { setConnectionStatus('success'); setAuthId(authorizationId); // Authorization ID can be used to fetch account details // Example: GET /api/v1/accounts?authorizationId={authorizationId} }; const handleError = (data: { statusCode: string; detail: string; errorCode?: string }) => { setConnectionStatus('error'); setErrorDetails(`Error ${data.statusCode}: ${data.detail}`); }; const handleExit = () => { console.log('User closed the connection flow'); setConnectionStatus('idle'); }; const closeModal = () => { setConnectionStatus('idle'); }; // Hook automatically listens for messages from allowed SnapTrade origins: // - https://app.snaptrade.com // - https://connect.snaptrade.com // - https://app.staging.snaptrade.com useWindowMessage({ handleSuccess, handleError, handleExit, close: closeModal, }); return (
{connectionStatus === 'success' && (
Connected successfully! Auth ID: {authId}
)} {connectionStatus === 'error' && (
Connection failed: {errorDetails}
)} {/* Render custom iframe or connection UI */}
); }; export default CustomConnectionPortal; ``` -------------------------------- ### Integrate Brokerage Connection Modal with SnapTradeReact Source: https://context7.com/passiv/snaptrade-react/llms.txt Use the SnapTradeReact component to render the brokerage connection portal in a modal. It requires a login link generated from the SnapTrade API and provides callbacks for success, error, and user exit events. Ensure the modal's overlay has a sufficient z-index for proper display. ```tsx import { useState } from 'react'; import { SnapTradeReact } from 'snaptrade-react'; const BrokerageConnection = () => { const [isOpen, setIsOpen] = useState(false); const [loginLink, setLoginLink] = useState(null); const initiateConnection = async () => { // Call SnapTrade API to generate redirect link const response = await fetch('https://api.snaptrade.com/api/v1/snapTrade/login', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer YOUR_API_KEY' }, body: JSON.stringify({ userId: 'user-123', userSecret: 'user-secret' }) }); const data = await response.json(); setLoginLink(data.redirectURI); setIsOpen(true); }; const handleSuccess = (authorizationId: string) => { console.log('Connection successful! Authorization ID:', authorizationId); setIsOpen(false); // Fetch connected accounts or update UI }; const handleError = (error: { statusCode: string; detail: string; errorCode?: string }) => { console.error('Connection error:', error.detail); console.error('Status code:', error.statusCode); // Display error message to user }; const handleExit = () => { console.log('User exited without completing connection'); }; const handleClose = () => { setIsOpen(false); }; return (
); }; export default BrokerageConnection; ``` -------------------------------- ### Connect Brokerage Component Source: https://github.com/passiv/snaptrade-react/blob/main/README.md A React component that uses the SnapTradeReact modal to initiate the brokerage connection process. It requires a function to generate a redirect URI and manages the modal's open state. ```jsx import { useState } from 'react'; import { SnapTradeReact } from 'snaptrade-react'; const ConnectBrokerage = () => { const [open, setOpen] = useState(false); const [redirectLink, setRedirectLink] = useState(null); const connectionProcess = () => { // call "https://api.snaptrade.com/api/v1/snapTrade/login" to generate a redirect link const link = getRedirectURI(); // update the state with the generated link setRedirectLink(link); // update the "open" state to show the modal setOpen(true); }; return (
{/* your Connect button */} setOpen(false)} />
); }; export default ConnectBrokerage; ``` -------------------------------- ### Using useWindowMessage Hook in React Source: https://github.com/passiv/snaptrade-react/blob/main/README.md This hook listens for window messages to handle success, error, exit, and close modal events. Ensure all necessary callback functions are passed as props. ```javascript import { useEffect } from 'react'; import { useWindowMessage } from 'snaptrade-react/hooks/useWindowMessage'; const MyComponent = () => { const onSuccess = (data) => { console.log('Success:', data); }; const onError = (data) => { console.error('Error:', data); }; const onExit = () => { console.log('Exit'); }; const close = () => { console.log('Close'); }; useWindowMessage({ handleSuccess: onSuccess, handleError: onError, handleExit: onExit, close: close, }); return
My Component
; }; export default MyComponent; ``` -------------------------------- ### Handle Brokerage Connection Errors with ErrorData Type Source: https://context7.com/passiv/snaptrade-react/llms.txt This TypeScript interface defines the structure of error data returned upon connection failure. Use it to properly handle and display error information. ```tsx import type { ErrorData } from 'snaptrade-react'; const handleConnectionError = (error: ErrorData) => { // ErrorData structure: // { // statusCode: string; // HTTP status code (e.g., "400", "401", "500") // detail: string; // Human-readable error description // errorCode?: string; // Optional specific error code from SnapTrade // } switch (error.statusCode) { case '401': console.error('Authentication failed:', error.detail); // Redirect to login or refresh tokens break; case '400': console.error('Bad request:', error.detail); // Display validation error to user break; case '500': console.error('Server error:', error.detail); // Show generic error message, suggest retry break; default: console.error(`Error [${error.errorCode || 'UNKNOWN'}]`, error.detail); } }; ``` -------------------------------- ### Enable Dark Mode for SnapTradeReact Component Source: https://context7.com/passiv/snaptrade-react/llms.txt The SnapTradeReact component automatically detects dark mode from the login link URL parameters. You can also override styles with custom CSS. ```tsx import { useState } from 'react'; import { SnapTradeReact } from 'snaptrade-react'; const DarkModeConnection = () => { const [isOpen, setIsOpen] = useState(false); // Login link with dark mode enabled // The component reads the darkMode query parameter and adjusts styling const darkModeLoginLink = 'https://app.snaptrade.com/connect?darkMode=true&token=xyz'; // When darkMode=true: // - Modal overlay defaults to 'rgba(0, 0, 0, 0.75)' instead of white // - Modal content background changes to '#0a0a0a' // You can still override with custom styles return ( setIsOpen(false)} style={{ overlay: { backgroundColor: 'rgba(30, 30, 30, 0.9)', // Custom dark overlay zIndex: 2000 } }} /> ); }; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.