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

# Using Variables in Themes

> Learn how to use collected configuration variables in your Salesive themes

Once users fill out your configuration form, the data is stored in `salesive.config.json`. This guide shows you how to access and use these variables in your theme.

## Configuration File Structure

When a user submits your form, their data is saved to `salesive.config.json`:

```json theme={null}
{
    "name": "my-theme",
    "version": "1.0.0",
    "description": "My Salesive Theme",
    "author": "Theme Developer",
    "errorHandling": {
        "reportErrors": false,
        "errorReportingUrl": "",
        "showComponentStack": true,
        "showReloadButton": true,
        "customErrorMessages": {
            "default": "Something went wrong in the application.",
            "network": "Network error. Please check your connection.",
            "notFound": "The requested resource was not found."
        }
    },
    "variables": {
        "heroTitle": "Welcome to My Store",
        "heroImage": "https://files.salesive.com/api/files/abc123",
        "primaryColor": "#0d65d9",
        "phoneNumber": "+1 (555) 123-4567",
        "email": "contact@example.com"
    }
}
```

## Variable Structure

All form field values are stored in the `variables` object, using the field `id` as the key:

<CodeGroup>
  ```json Form Schema theme={null}
  {
    "id": "heroTitle",
    "type": "text",
    "label": "Hero Title",
    "default": "Welcome"
  }
  ```

  ```json Config Output theme={null}
  {
      "variables": {
          "heroTitle": "Welcome to My Store"
      }
  }
  ```
</CodeGroup>

## Accessing Variables

Salesive provides the `salesive-dev-tools` package for accessing configuration variables in your React themes.

## Installation

Install the package in your theme project:

```bash theme={null}
npm install salesive-dev-tools
# or
yarn add salesive-dev-tools
# or
pnpm add salesive-dev-tools
```

## Setup

### 1. Configure Vite Plugin

Add the Salesive config plugin to your `vite.config.js`:

```js theme={null}
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { salesiveConfigPlugin } from "salesive-dev-tools";

export default defineConfig({
    plugins: [react(), salesiveConfigPlugin()],
});
```

<Note>
  The plugin automatically injects your config into the application during
  development.
</Note>

### 2. Create Configuration File

Your `salesive.config.json` file should be in the project root with variables from the form:

```json theme={null}
{
    "name": "my-theme",
    "version": "1.0.0",
    "description": "My Salesive Theme",
    "author": "Your Name",
    "variables": {
        "heroTitle": "Welcome to My Store",
        "heroImage": "https://files.salesive.com/api/files/abc123",
        "primaryColor": "#0d65d9",
        "phoneNumber": "+1 (555) 123-4567",
        "email": "contact@example.com"
    }
}
```

## Using Variables in React Components

### Using the React Hook

The `useSalesiveConfig` hook is the primary way to access variables in React components:

```jsx theme={null}
import { useSalesiveConfig } from "salesive-dev-tools";

function Hero() {
    // Get specific variables
    const heroTitle = useSalesiveConfig("heroTitle");
    const heroImage = useSalesiveConfig("heroImage");
    const primaryColor = useSalesiveConfig("primaryColor");

    return (
        <div
            className="hero"
            style={{
                backgroundImage: `url(${heroImage})`,
                backgroundColor: primaryColor,
            }}
        >
            <h1>{heroTitle}</h1>
        </div>
    );
}
```

### Getting All Variables

You can also retrieve all variables at once:

```jsx theme={null}
import { useSalesiveConfig } from "salesive-dev-tools";

function Hero() {
    // Get all variables
    const allVariables = useSalesiveConfig();

    return (
        <div
            className="hero"
            style={{ backgroundImage: `url(${allVariables.heroImage})` }}
        >
            <h1>{allVariables.heroTitle}</h1>
            <p>Contact: {allVariables.email}</p>
        </div>
    );
}
```

### Using in Non-Component Code

For accessing config outside of React components, use the helper function:

```js theme={null}
import { getSalesiveConfig } from "salesive-dev-tools";

// Get a specific variable
const appName = getSalesiveConfig("heroTitle");

// Get all variables
const allVariables = getSalesiveConfig();
```

## Dynamic Configuration Updates

Update configuration values at runtime and all components will automatically re-render:

```jsx theme={null}
import { updateSalesiveConfig, setSalesiveConfig } from "salesive-dev-tools";

// Update a specific variable
setSalesiveConfig("primaryColor", "#ff0000");

// Update multiple variables at once
updateSalesiveConfig({
    variables: {
        primaryColor: "#ff0000",
        heroTitle: "Updated Title",
    },
});

// Use a function to update based on previous state
updateSalesiveConfig((prevConfig) => ({
    ...prevConfig,
    variables: {
        ...prevConfig.variables,
        heroTitle: `${prevConfig.variables["heroTitle"]} - Updated`,
    },
}));
```

<Note>
  All components using `useSalesiveConfig` will automatically update when
  configuration changes.
</Note>

### CSS Variables

The plugin automatically injects all variables as CSS custom properties:

```jsx theme={null}
function ThemedButton() {
    const primaryColor = useSalesiveConfig("primaryColor");

    return <button style={{ backgroundColor: primaryColor }}>Click Me</button>;
}
```

Or use the auto-injected CSS variables directly:

```css theme={null}
.button-primary {
    background-color: var(--primaryColor);
}

.text-accent {
    color: var(--accentColor);
}
```

## Variable Types and Usage

### Text Variables

Use text variables for content throughout your theme:

```jsx theme={null}
import { useSalesiveConfig } from "salesive-dev-tools";

function ContactInfo() {
    const storeName = useSalesiveConfig("storeName");
    const aboutUs = useSalesiveConfig("aboutUsDescription");
    const email = useSalesiveConfig("contactEmail");
    const phone = useSalesiveConfig("phoneNumber");
    const website = useSalesiveConfig("websiteUrl");

    return (
        <div>
            <h1>{storeName}</h1>
            <p>{aboutUs}</p>
            <a href={`mailto:${email}`}>{email}</a>
            <a href={`tel:${phone}`}>{phone}</a>
            <a href={website} target="_blank">
                Visit Website
            </a>
        </div>
    );
}
```

### Media Variables

#### Single Image

```jsx theme={null}
import { useSalesiveConfig } from "salesive-dev-tools";

function Logo() {
    const logo = useSalesiveConfig("logo");

    return <img src={logo} alt="Store Logo" className="logo" />;
}
```

#### Multiple Images (Array)

```jsx theme={null}
import { useSalesiveConfig } from "salesive-dev-tools";

function BannerCarousel() {
    const heroBanners = useSalesiveConfig("heroBanners");

    return (
        <div className="carousel">
            {heroBanners.map((banner, index) => (
                <img key={index} src={banner} alt={`Banner ${index + 1}`} />
            ))}
        </div>
    );
}
```

### Color Variables

Use color variables for theming:

```jsx theme={null}
import { useSalesiveConfig } from "salesive-dev-tools";

function ThemedSection() {
    const primaryColor = useSalesiveConfig("primaryColor");
    const textColor = useSalesiveConfig("textColor");

    return (
        <div style={{ backgroundColor: primaryColor }}>
            <h2 style={{ color: textColor }}>Title</h2>
        </div>
    );
}
```

Or use CSS with auto-injected variables:

```css theme={null}
.hero {
    background-color: var(--primaryColor);
}

.button {
    background-color: var(--accentColor);
    color: var(--buttonTextColor);
}

.link {
    color: var(--secondaryColor);
}
```

### Select Variables

#### Single Select

```jsx theme={null}
import { useSalesiveConfig } from "salesive-dev-tools";

function Content() {
    const layoutStyle = useSalesiveConfig("layoutStyle");

    // Use in className
    return (
        <div className={`content content--${layoutStyle}`}>
            {/* Content here */}
        </div>
    );
}

// Or conditional rendering
function LayoutContent() {
    const layoutStyle = useSalesiveConfig("layoutStyle");

    if (layoutStyle === "grid") {
        return <GridLayout />;
    } else if (layoutStyle === "list") {
        return <ListLayout />;
    }
    return <MasonryLayout />;
}
```

#### Multi Select (Array)

```jsx theme={null}
import { useSalesiveConfig } from "salesive-dev-tools";

function Features() {
    const enabledFeatures = useSalesiveConfig("enabledFeatures");

    return (
        <>
            {enabledFeatures.includes("wishlist") && <WishlistButton />}
            {enabledFeatures.includes("cart") && <CartIcon />}
            {enabledFeatures.includes("reviews") && <ReviewSection />}
        </>
    );
}
```

## Default Values

Always provide fallback values in case a variable is not set:

```jsx theme={null}
import { useSalesiveConfig } from "salesive-dev-tools";

function Hero() {
    const heroTitle = useSalesiveConfig("heroTitle") || "Welcome to Our Store";
    const primaryColor = useSalesiveConfig("primaryColor") || "#0d65d9";

    return (
        <div style={{ backgroundColor: primaryColor }}>
            <h1>{heroTitle}</h1>
        </div>
    );
}
```

## Complete Example

Here's a complete example showing how to use various variable types:

<Tabs>
  <Tab title="Form Schema">
    ```json theme={null}
    {
      "pages": [
        {
          "page": "home",
          "title": "Home Page",
          "sections": [
            {
              "id": "hero",
              "title": "Hero Section",
              "fields": [
                {
                  "id": "heroTitle",
                  "type": "text",
                  "inputType": "text",
                  "label": "Hero Title",
                  "default": "Welcome",
                  "required": true
                },
                {
                  "id": "heroSubtitle",
                  "type": "text",
                  "inputType": "textarea",
                  "label": "Hero Subtitle",
                  "required": false
                },
                {
                  "id": "heroBanners",
                  "type": "media",
                  "mediaType": "image",
                  "label": "Hero Banners",
                  "multiple": true,
                  "maxItems": 5,
                  "required": true
                }
              ]
            },
            {
              "id": "colors",
              "title": "Brand Colors",
              "fields": [
                {
                  "id": "primaryColor",
                  "type": "color",
                  "label": "Primary Color",
                  "default": "#0d65d9",
                  "required": true
                }
              ]
            }
          ]
        }
      ]
    }
    ```
  </Tab>

  <Tab title="Config Output">
    ```json theme={null}
    {
      "variables": {
        "heroTitle": "Welcome to Paradise Store",
        "heroSubtitle": "Discover amazing products at great prices",
        "heroBanners": [
          "https://files.salesive.com/api/files/banner1.jpg",
          "https://files.salesive.com/api/files/banner2.jpg",
          "https://files.salesive.com/api/files/banner3.jpg"
        ],
        "primaryColor": "#ff6b6b"
      }
    }
    ```
  </Tab>

  <Tab title="Theme Usage">
    ```jsx theme={null}
    import { useSalesiveConfig } from "salesive-dev-tools";

    function Hero() {
    const heroTitle = useSalesiveConfig("heroTitle");
    const heroSubtitle = useSalesiveConfig("heroSubtitle");
    const heroBanners = useSalesiveConfig("heroBanners");
    const primaryColor = useSalesiveConfig("primaryColor");

    return (
    <section
    className="hero"
    style={{
            backgroundColor: primaryColor,
            backgroundImage: `url(${heroBanners[0]})`
          }} >
    <div className="hero-content">
    <h1>{heroTitle}</h1>
    {heroSubtitle && <p>{heroSubtitle}</p>}

            <div className="banner-thumbnails">
              {heroBanners.map((banner, index) => (
                <img
                  key={index}
                  src={banner}
                  alt={`Banner ${index + 1}`}
                  className="thumbnail"
                />
              ))}
            </div>
          </div>
        </section>

    );
    }

    ```
  </Tab>
</Tabs>

## Best Practices

<Tip>
  **Always Provide Defaults**

  Never assume a variable will be set. Always provide fallback values to prevent broken layouts when variables are missing.
</Tip>

<Warning>
  **Sanitize User Input**

  If displaying user-provided text or URLs, sanitize the input to prevent XSS attacks, especially for HTML rendering.
</Warning>

<Check>
  **Variable Naming**

  * Use descriptive, semantic names: `heroTitle` instead of `title1`
  * Follow camelCase convention: `primaryColor`, `phoneNumber`
  * Be consistent across your entire theme
  * Document which variables are required vs optional
</Check>

## Testing Variables

### Development Testing

Create a test `salesive.config.json` with sample data:

```json theme={null}
{
  "variables": {
    "heroTitle": "Test Hero Title",
    "heroImage": "https://via.placeholder.com/1920x1080",
    "primaryColor": "#ff0000",
    "phoneNumber": "+1 (555) 123-4567"
  }
}
```

### Production Validation

Before deploying your theme:

1. Test with minimal required variables only
2. Test with all variables filled
3. Test with very long text values
4. Test with special characters in text fields
5. Test with various image sizes and formats
6. Test with all possible select option combinations

## Variable Documentation

Document your theme's variables in a `README.md`:

```markdown theme={null}
## Required Variables

-   `heroTitle` (string): Main hero section title
-   `primaryColor` (hex): Primary brand color
-   `logo` (image URL): Store logo

## Optional Variables

-   `heroSubtitle` (string): Optional hero subtitle
-   `secondaryColor` (hex): Secondary brand color (default: #64748b)
```

This helps users understand what each variable does and which ones are required.

## Next Steps

<CardGroup cols={2}>
  <Card title="View Examples" icon="lightbulb" href="/form-builder/examples">
    See complete examples of form schemas and their usage
  </Card>

  <Card title="Schema Structure" icon="sitemap" href="/form-builder/schema-structure">
    Review the complete schema structure reference
  </Card>
</CardGroup>
