> ## Documentation Index
> Fetch the complete documentation index at: https://docs.straddle.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Straddle Embed React component

> Integrate and customize the Straddle Embed onboarding form in your React application, including theming, callbacks, and merchant verification flows.

The Embed component provides a seamless way to integrate Straddle forms into your React application. This guide covers everything you need to know about implementing and customizing the component.

<Info>
  This component automatically handles responsive layouts and dynamic height adjustment, making it ideal for a variety of application layouts and screen sizes.
</Info>

## Key Features

<CardGroup cols={2}>
  <Card title="Responsive Layout" icon="arrows-maximize">
    Flexible width options from narrow to full-width to suit any layout needs
  </Card>

  <Card title="Dynamic Height" icon="arrows-up-down">
    Automatically adjusts height based on form content
  </Card>

  <Card title="TypeScript Support" icon="code">
    Built-in TypeScript definitions for reliable type checking
  </Card>

  <Card title="Error Handling" icon="shield-check">
    Built-in error handling with customizable fallback options
  </Card>
</CardGroup>

## Installation and Setup

<Card title="Visit the Github Repo" icon="github" color="#000000" horizontal href="https://github.com/straddleio/embed" />

<Steps>
  <Step title="Install Dependencies">
    Ensure React is installed in your project. The Straddle Embed Component is compatible with React 16.8 and above.
  </Step>

  <Step title="Add Component Files">
    Copy the `StraddleEmbedComponent.tsx` file into your project's component directory.
  </Step>

  <Step title="Import and Use">
    Import and implement the component in your application:

    ```tsx theme={null}
    import React from 'react';
    import StraddleEmbedComponent from './path/to/StraddleEmbedComponent';

    function MyComponent() {
      return (
        <StraddleEmbedComponent 
          platformId="your-platform-id" 
          env="your-env-value" 
        />
      );
    }
    ```
  </Step>
</Steps>

## Component Props

<ResponseField name="platformId" type="string" required>
  Your unique Straddle platform identifier. This is used to associate the embedded form with your specific account or configuration.
</ResponseField>

<ResponseField name="env" type="string" required>
  A string value representing the Straddle environment in which form submissions are created (e.g., `production`, `sandbox`).
</ResponseField>

<ResponseField name="maxWidth" type="string" default="'full'">
  Controls the component's maximum width. Available options:

  <Expandable title="Width Options">
    <ResponseField name="narrow" type="string">
      Sets maximum width to 384px (max-w-sm)
    </ResponseField>

    <ResponseField name="medium" type="string">
      Sets maximum width to 768px (max-w-3xl)
    </ResponseField>

    <ResponseField name="wide" type="string">
      Sets maximum width to 1024px (max-w-5xl)
    </ResponseField>

    <ResponseField name="full" type="string">
      Uses 100% of container width
    </ResponseField>

    <ResponseField name="auto" type="string">
      Removes max-width constraint
    </ResponseField>
  </Expandable>
</ResponseField>

## Implementation Examples

### Basic Usage

<CodeGroup>
  ```tsx Basic theme={null}
  import React from 'react';
  import StraddleEmbedComponent from './StraddleEmbedComponent';

  function MyComponent() {
    return (
      <StraddleEmbedComponent 
        platformId="your-platform-id"
        env="sandbox" // Always use sandbox for testing
      />
    );
  }
  ```

  ```tsx With Custom Width theme={null}
  import React from 'react';
  import StraddleEmbedComponent from './StraddleEmbedComponent';

  function MyComponent() {
    return (
      <StraddleEmbedComponent 
        platformId="your-platform-id"
        env="sandbox"
        maxWidth="medium"
      />
    );
  }
  ```
</CodeGroup>

### Responsive Implementation

<CodeGroup>
  ```tsx Responsive Example theme={null}
  import React, { useState, useEffect } from 'react';
  import StraddleEmbedComponent from './StraddleEmbedComponent';

  function ResponsiveStraddleEmbed() {
    const [maxWidth, setMaxWidth] = useState('full');

    useEffect(() => {
      const mediaQuery = window.matchMedia('(min-width: 768px)');
      
      const handleMediaQueryChange = (e) => {
        setMaxWidth(e.matches ? 'medium' : 'full');
      };

      mediaQuery.addListener(handleMediaQueryChange);
      handleMediaQueryChange(mediaQuery);

      return () => mediaQuery.removeListener(handleMediaQueryChange);
    }, []);

    return (
      <StraddleEmbedComponent 
        platformId="your-platform-id"
        env="sandbox"
        maxWidth={maxWidth}
      />
    );
  }
  ```
</CodeGroup>

## Configuration Details

### URL Parameters

The Straddle embed URL includes several preconfigured parameters that control the form's appearance and behavior. These parameters are automatically set in the component for optimal integration. The `env` value is not injected into the URL, but is instead provided as a separate data attribute, making it accessible to the embedded form internally.

<ResponseField name="URL Parameters" type="object">
  <Expandable title="Available Parameters">
    <ResponseField name="alignLeft" type="boolean">
      When set to 1, aligns all content to the left of the container
    </ResponseField>

    <ResponseField name="hideTitle" type="boolean">
      When set to 1, removes the default form title
    </ResponseField>

    <ResponseField name="transparentBackground" type="boolean">
      When set to 1, makes the form background transparent to match your application
    </ResponseField>

    <ResponseField name="dynamicHeight" type="boolean">
      When set to 1, enables automatic height adjustment based on form content
    </ResponseField>

    <ResponseField name="embed" type="boolean">
      When set to 1, optimizes the form for embedded display
    </ResponseField>
  </Expandable>
</ResponseField>

### Using the `env` Prop

<Info>
  The `env` prop allows you to indicate whether the embedded Straddle form should create a test account (in your platform's sandbox environment) or a real, production-level account. This is particularly useful when you're testing webhook integrations, trialing new features, or verifying payment flows before going live.
</Info>

**How It Works:**

* **Sandbox Environment:**\
  When `env` is set to a value indicating a sandbox or test environment (e.g., `env="sandbox"`), the embedded form will create new accounts in your sandbox environment. This ensures you can safely experiment, test your integrations, and verify webhook responses without impacting live data or existing real accounts.
* **Production Environment:**\
  When `env` is set to `production`, the embedded form operates against your real, production-level environment. Accounts created, data submitted, and webhooks triggered from this embedded form will reflect actual usage scenarios and should be treated as live, customer-facing transactions.

**No Direct URL Changes:**\
The `env` value is not appended to the Straddle form URL. Instead, it's passed as a data attribute on the iframe (i.e., `env`), allowing the form itself (within the iframe) to interpret and act upon the environment setting. This ensures that the same URL can be used consistently, while the underlying logic—such as which database endpoints or webhook routes to invoke—is dynamically adjusted based on `env`.

**Recommended Usage:**

* Use `env="sandbox"` whenever you're testing new integrations, verifying that your webhook listeners work correctly, or experimenting with new features.
* Switch to `env="production"` only when you're ready for real-world usage, ensuring that account creations, messages, and webhooks are fully integrated into your live environment.

### Dynamic Height Behavior

<Info>
  The component implements a sophisticated height management system that combines fixed minimum heights with dynamic content adjustment.
</Info>

The dynamic height functionality works through two mechanisms:

1. The `dynamicHeight=1` URL parameter enables the embed to communicate its content height.
2. A minimum height of 500px is enforced via inline styles to prevent layout shifts during loading.

<Warning>
  Modifying the minimum height may cause layout instability during the initial load. The default 500px value is recommended for most use cases.
</Warning>

### TypeScript Integration

The component includes comprehensive TypeScript definitions for enhanced development experience:

<CodeGroup>
  ```typescript Type Definitions theme={null}
  interface StraddleEmbedComponentProps {
    platformId: string;
    env: string; // Now included as a required prop
    maxWidth?: 'narrow' | 'medium' | 'wide' | 'full' | 'auto';
  }
  ```

  ```typescript Usage with Types theme={null}
  import React from 'react';
  import StraddleEmbedComponent from './StraddleEmbedComponent';

  const MyComponent: React.FC = () => {
    return (
      <StraddleEmbedComponent 
        platformId="your-platform-id"
        env="production"
        maxWidth="medium"
      />
    );
  };
  ```
</CodeGroup>

### Script Loading and Error Handling

The component implements robust script loading with automatic fallbacks:

<Steps>
  <Step title="Primary Script Loading">
    Attempts to load the Straddle embed script from '[https://forms.straddle.com/embed.js](https://forms.straddle.com/embed.js)'
  </Step>

  <Step title="Fallback Mechanism">
    If the script fails to load or execute properly, the component falls back to direct iframe source setting
  </Step>

  <Step title="Error Recovery">
    Implements comprehensive error handling for both script loading and execution failures
  </Step>
</Steps>

<CodeGroup>
  ```typescript Error Handling Implementation theme={null}
  const handleScriptError = () => {
    console.error('Failed to load the Straddle embed script.')
    loadEmbeds()
  }

  if (!existingScript) {
    const script = document.createElement('script')
    script.src = embedScriptSrc
    script.async = true
    script.onload = loadEmbeds
    script.onerror = handleScriptError
    document.body.appendChild(script)
  }
  ```
</CodeGroup>

## Advanced Usage

### Error Handling

<CodeGroup>
  ```tsx Error Boundary theme={null}
  import React from 'react';
  import ErrorBoundary from './ErrorBoundary';
  import StraddleEmbedComponent from './StraddleEmbedComponent';

  function MyComponent() {
    return (
      <ErrorBoundary fallback={<div>Error loading Straddle form</div>}>
        <StraddleEmbedComponent 
          platformId="your-platform-id"
          env="production"
        />
      </ErrorBoundary>
    );
  }
  ```
</CodeGroup>

## Best Practices

<AccordionGroup>
  <Accordion title="Platform ID Management">
    While your `platformId` is not secret, it is recommended to store it in environment variables or a secure configuration management system.
  </Accordion>

  <Accordion title="Environment Value (env)">
    Use the `env` prop to indicate the deployment environment (such as production, staging, or sandbox) to the embedded form. The form can then read this value and adjust its behavior or display accordingly.
  </Accordion>

  <Accordion title="Width Selection">
    Choose the appropriate maxWidth based on your layout requirements. Use 'medium' for standard forms and 'full' for responsive layouts.
  </Accordion>

  <Accordion title="Error Handling">
    Implement error boundaries to gracefully handle any loading or rendering issues with the embed component.
  </Accordion>

  <Accordion title="Performance">
    The component uses lazy loading by default. Ensure the container has sufficient space to prevent layout shifts during loading.
  </Accordion>
</AccordionGroup>

### Custom Component Integration

The Straddle Embed Component can be wrapped with custom components to extend its functionality:

<CodeGroup>
  ```tsx Custom Container theme={null}
  import React from 'react';
  import StraddleEmbedComponent from './StraddleEmbedComponent';

  const CustomStraddleContainer: React.FC = () => {
    return (
      <div className="my-custom-container">
        <h2>Account Setup</h2>
        <StraddleEmbedComponent 
          platformId="your-platform-id"
          env="production"
          maxWidth="medium"
        />
        <div className="support-text">
          Need help? Contact support
        </div>
      </div>
    );
  };
  ```

  ```tsx With Loading State theme={null}
  import React, { useState } from 'react';
  import StraddleEmbedComponent from './StraddleEmbedComponent';

  const LoadingAwareStraddle: React.FC = () => {
    const [isLoading, setIsLoading] = useState(true);

    return (
      <div>
        {isLoading && <LoadingSpinner />}
        <StraddleEmbedComponent 
          platformId="your-platform-id"
          env="sandbox"
          onLoad={() => setIsLoading(false)}
        />
      </div>
    );
  };
  ```
</CodeGroup>

### Styling Integration

The component uses Tailwind CSS classes for layout management. Here's how different width options map to Tailwind classes:

<ResponseField name="Width Classes" type="object">
  <Expandable title="Tailwind Mappings">
    <ResponseField name="narrow">
      Uses `max-w-sm` (384px)
    </ResponseField>

    <ResponseField name="medium">
      Uses `max-w-3xl` (768px)
    </ResponseField>

    <ResponseField name="wide">
      Uses `max-w-5xl` (1024px)
    </ResponseField>

    <ResponseField name="full">
      Uses `w-full` (100%)
    </ResponseField>

    <ResponseField name="auto">
      No width constraint
    </ResponseField>
  </Expandable>
</ResponseField>

<Note>
  The component's container uses `flex justify-center w-full` to ensure proper centering and responsive behavior.
</Note>

### Performance Considerations

<AccordionGroup>
  <Accordion title="Script Loading">
    The embed script is loaded asynchronously to prevent blocking page rendering. The component uses a single-instance pattern to avoid loading multiple copies of the script.
  </Accordion>

  <Accordion title="Resource Management">
    The component properly cleans up event listeners and script references on unmount to prevent memory leaks.
  </Accordion>

  <Accordion title="Layout Stability">
    The minimum height setting helps prevent Cumulative Layout Shift (CLS) during form loading.
  </Accordion>
</AccordionGroup>

## Troubleshooting

<Note>
  If you encounter issues with the embed component, verify these common points:
</Note>

<Steps>
  <Step title="Script Loading">
    Ensure the Straddle embed script ([https://forms.straddle.com/embed.js](https://forms.straddle.com/embed.js)) is loading correctly in your network tab.
  </Step>

  <Step title="Platform ID & env">
    Verify your `platformId` and `env` values are correct and properly formatted. The `env` prop should match the environment context you intend the form to operate within.
  </Step>

  <Step title="Container Size">
    Check that the parent container provides adequate space for the embed to render properly.
  </Step>

  <Step title="Network Connection">
    Verify there are no network issues preventing the iframe content from loading.
  </Step>
</Steps>

## Related Resources

<CardGroup cols={2}>
  <Card title="API Documentation" icon="book" href="/api-reference">
    Complete API reference for Embed
  </Card>

  <Card title="Quick Start Guide" icon="code" href="/guides/quickstart">
    Get started with implementation examples
  </Card>

  <Card title="Sandbox Testing" icon="wrench" href="/guides/resources/sandbox-platform">
    Test your implementation in our sandbox environment
  </Card>

  <Card title="Community Support" icon="headset" href="https://strddl.co/mmunity">
    Join our Slack community for additional help
  </Card>
</CardGroup>
