# react-edit-to-html

`react-edit-to-html` is a premium, highly customizable, responsive HTML editor and visual template builder for creating dynamic HTML layouts. It is perfect for generating backend templates (invoices, shipping lists, email templates, billing letters, reports, PDF documents, etc.) populated with dynamic data.

---

## 🚀 Live Online Demo

Click the button below to try out `react-edit-to-html` live on CodeSandbox:

[![Edit react-edit-to-html](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/p/devbox/react-edit-to-html-forked-tfsm4n)

The editor allows you to structure tables, images, text, and barcodes, preview them in real time with custom mock values, configure loop templates for multiple template engines (**TypeScript (`ts`)**, **JavaScript (`js`) ES6 Template Literals**, Handlebars, Liquid, Scriban, .NET, C#/Razor), and export clean, production-ready HTML files.

---

## 🌐 Multi-Framework & TypeScript/JavaScript Support

Yes! **`react-edit-to-html` is built with TypeScript (`.ts`/`.tsx`) and supports all JavaScript/TypeScript frameworks**:
- **React & Next.js** (Native TSX/JSX component)
- **Vue 3 & Vue 2** (via `mountHtmlEditor` helper)
- **Angular** (via `mountHtmlEditor` helper)
- **Svelte & SvelteKit** (via `mountHtmlEditor` helper)
- **Vanilla JavaScript / TypeScript** (plain HTML, jQuery, PHP, Laravel, Rails, ASP.NET)

The package includes full **TypeScript declaration files (`.d.ts`)** and exports `mountHtmlEditor(container, props)` and `unmountHtmlEditor(container)` for non-React or plain JS environments.

---

## 🌟 Key Features & Highlights

- 🛠 **Drag-and-Drop Canvas Editor:** Select element blocks (headings, paragraphs, tables, images, barcodes) from the sidebar and drag them onto the paper canvas.
- 🔷 **Full TypeScript & JavaScript Flexibility:** Built in TypeScript with full type definitions (`.d.ts`) + `mountHtmlEditor` helper for Vue, Angular, Svelte, and Vanilla JS.
- 📊 **Live Dummy Data Preview Engine:** Pass sample placeholder data (`dummyData`) to substitute placeholders (`{{carrier_code}}`, `{{sender.name}}`, etc.), table cells, and barcodes directly in the canvas. Toggle between template placeholder markers and live dummy data view with a single click.
- 🟨 **JS/TS ES6 Template Literals (`js` / `ts`):** Dynamic map looping (`${items.map(item => \`...\`).join('')}`) alongside Handlebars, Liquid, Scriban, and C#/Razor syntaxes.
- 🔄 **Multi-Syntax Loop Templates:** Toggle template engines (`templatingLanguage="js"`, `"ts"`, `"handlebars"`, `"liquid"`, `"scriban"`, `"csharp"`, `"dotnet"`) for dynamic table looping.
- 🖼 **Image Alignment & Position Controls:** Visual alignment controls (Left, Center, Right) for images and barcodes in both live canvas and exported HTML markup.
- 📊 **Dynamic Mock Visualizer:** View variables substituted instantly with mock data. Edit mock values for placeholders and raw JSON rows directly in the sidebar.
- 🎨 **Advanced Styles & Layouts:** Customize padding, margin, block widths, element sizing, and colors for a true WYSIWYG editing experience.
- 🔤 **Custom Typography:** Register custom font sizes, weights, and Google Fonts directly in the panel.
- 🖼 **Custom Image Types & SVG Barcodes:** Register custom graphic categories (e.g., Signature, Logo, Banner, Watermark, Barcode) on the fly with clean SVG base64 image placeholders.
- 📱 **Fully Responsive Layout:** Automatically stacks vertically on smaller screens and side-by-side on desktop screens.
- ⚡ **PDF & HTML Importing:** Import existing HTML templates or parse digital PDF text layers directly into editable canvas blocks.

---

## 💡 Live Dummy Data Substitution (`dummyData`)

You can pass real sample data via the `dummyData` prop. When present, a **"View Dummy Data"** button appears in the toolbar, enabling users to toggle between template placeholder tags (`{{sender.name}}`) and populated live values (`BEO Software Solutions GmbH`).

```tsx
import HtmlEditor from 'react-edit-to-html';

export default function App() {
  return (
    <HtmlEditor
      dummyData={{
        placeholders: {
          carrier_code: "DHL",
          product_code: "EXPRESS_DOMESTIC",
          shipment_reference: "REF-884920",
          "sender.name": "BEO Software Solutions GmbH",
          "sender.postal_code": "60549",
          "sender.city": "Frankfurt am Main",
          tracking_number: "1Z9999999999999999",
          order_number: "ORD-2026-99201"
        }
      }}
    />
  );
}
```

---

---

## 📦 Installation

Install the package via npm:

```bash
npm install react-edit-to-html
```

Make sure to import the CSS stylesheet in your application:

```typescript
import 'react-edit-to-html/dist/react-edit-to-html.css';
// Or conveniently:
import 'react-edit-to-html/style.css';
```

---

## 💻 Integration Examples Across Frameworks

### 1. React / Next.js Example (TypeScript & JavaScript)

```tsx
import React from 'react';
import HtmlEditor from 'react-edit-to-html';
import type { TableSchemaInfo, PlaceholderItem } from 'react-edit-to-html';
import 'react-edit-to-html/dist/react-edit-to-html.css';

export default function ReactTemplateEditor() {
  const customTables: TableSchemaInfo[] = [
    {
      tableName: 'order_items',
      columns: [
        { columnName: 'Item Name', placeholder: '${item.name}', enabled: true },
        { columnName: 'SKU', placeholder: '${item.sku}', enabled: true },
        { columnName: 'Price', placeholder: '${item.price}', enabled: true }
      ],
      loop: true
    }
  ];

  return (
    <div style={{ height: '100vh', width: '100vw' }}>
      <HtmlEditor
        headerTitle="React Document Builder"
        tableSchemas={customTables}
        templatingLanguage="ts"
        onExport={(html: string) => console.log('Exported HTML:', html)}
      />
    </div>
  );
}
```

---

### 2. Vue 3 Example (Using `mountHtmlEditor`)

```vue
<template>
  <div ref="editorRef" style="height: 100vh; width: 100vw;"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { mountHtmlEditor, unmountHtmlEditor } from 'react-edit-to-html';
import 'react-edit-to-html/dist/react-edit-to-html.css';

const editorRef = ref<HTMLDivElement | null>(null);

onMounted(() => {
  if (editorRef.value) {
    mountHtmlEditor(editorRef.value, {
      headerTitle: 'Vue 3 Template Designer',
      templatingLanguage: 'js',
      onExport: (html: string) => console.log('Exported HTML from Vue:', html)
    });
  }
});

onUnmounted(() => {
  if (editorRef.value) unmountHtmlEditor(editorRef.value);
});
</script>
```

---

### 3. Angular Example (Using `mountHtmlEditor`)

```typescript
import { Component, ElementRef, ViewChild, AfterViewInit, OnDestroy } from '@angular/core';
import { mountHtmlEditor, unmountHtmlEditor } from 'react-edit-to-html';
import 'react-edit-to-html/dist/react-edit-to-html.css';

@Component({
  selector: 'app-html-editor',
  template: `<div #editorContainer style="height: 100vh; width: 100vw;"></div>`
})
export class HtmlEditorComponent implements AfterViewInit, OnDestroy {
  @ViewChild('editorContainer') container!: ElementRef<HTMLDivElement>;

  ngAfterViewInit() {
    mountHtmlEditor(this.container.nativeElement, {
      headerTitle: 'Angular Template Designer',
      templatingLanguage: 'ts',
      onExport: (html: string) => console.log('Exported HTML from Angular:', html)
    });
  }

  ngOnDestroy() {
    unmountHtmlEditor(this.container.nativeElement);
  }
}
```

---

### 4. Svelte Example (Using `mountHtmlEditor`)

```svelte
<script lang="ts">
  import { onMounted, onDestroy } from 'svelte';
  import { mountHtmlEditor, unmountHtmlEditor } from 'react-edit-to-html';
  import 'react-edit-to-html/dist/react-edit-to-html.css';

  let container: HTMLDivElement;

  onMounted(() => {
    mountHtmlEditor(container, {
      headerTitle: 'Svelte Document Builder',
      templatingLanguage: 'js',
      onExport: (html: string) => console.log('Exported HTML from Svelte:', html)
    });
  });

  onDestroy(() => {
    if (container) unmountHtmlEditor(container);
  });
</script>

<div bind:this={container} style="height: 100vh; width: 100vw;"></div>
```

---

### 5. Vanilla JavaScript / Plain HTML Example

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Vanilla JS HTML Editor</title>
  <link rel="stylesheet" href="node_modules/react-edit-to-html/dist/react-edit-to-html.css">
</head>
<body style="margin: 0;">
  <div id="editor-root" style="height: 100vh; width: 100vw;"></div>

  <script type="module">
    import { mountHtmlEditor } from './node_modules/react-edit-to-html/dist/index.js';

    mountHtmlEditor(document.getElementById('editor-root'), {
      headerTitle: 'Vanilla JavaScript Editor',
      templatingLanguage: 'js',
      onExport: function(html) {
        console.log('Exported HTML:', html);
      }
    });
  </script>
</body>
</html>
```

---

## 📋 Props Reference

```ts
type TableColumn = {
  columnName: string;
  placeholder: string;
  enabled?: boolean;
  loop?: boolean;
  columns?: TableColumn[];
};

type TableSchemaInfo = {
  tableName: string;
  columns: TableColumn[];
  loop: boolean;
  isNestable?: boolean;
  parentPath?: string;
  maxNestingDepth?: number;
  nestingPrefix?: string;
  showNestingLevel?: boolean;
  loopStartTag?: string;
  loopEndTag?: string;
  mockRows?: any[];
};

type PlaceholderItem = {
  label: string;
  placeholder: string;
  mockValue?: string;
};

interface DummyData {
  /** Map of placeholder keys to real string/number values, e.g. { "carrier_code": "DHL", "sender.name": "BEO Software" } */
  placeholders?: Record<string, string | number>;
  /** Fallback top-level properties directly accessible by key */
  [key: string]: any;
}

interface HtmlEditorProps {
  tableSchemas?: TableSchemaInfo[];
  placeholders?: PlaceholderItem[];
  dummyData?: DummyData;
  showDummyDataPreview?: boolean;
  onToggleDummyDataPreview?: (isApplied: boolean) => void;
  defaultLogo?: string;
  defaultBanner?: string;
  headerTitle?: string;
  headerSubtitle?: string;
  headerLogo?: React.ReactNode;
  typographySizes?: Array<{ label: string; value: string }>;
  typographyWeights?: Array<{ label: string; value: string }>;
  typographyFonts?: Array<{ label: string; value: string }>;
  templatingLanguage?: 'js' | 'ts' | 'handlebars' | 'liquid' | 'scriban' | 'dotnet' | 'csharp' | 'custom';
  loopSyntax?: 'for' | 'foreach' | 'each';
  onChange?: (blocks: CanvasBlock[]) => void;
  onExport?: (html: string) => void;
  onExportPdf?: (html: string) => void;
  /** Real-time callback prop to receive compiled template HTML code on demand / changes */
  getHTMLOutput?: (html: string) => void;
  initialBlocks?: CanvasBlock[];
  defaultStyles?: Record<string, Partial<TextStyle>>;
  showImportHtml?: boolean;
  showImportPdf?: boolean;
  showClearCanvas?: boolean;
  showPreview?: boolean;
  showExport?: boolean;
  showExportPdf?: boolean;
  /** Show or hide top header bar (defaults to true) */
  showHeader?: boolean;
  /** Controls position of the entire sidebar panel ('left' | 'right'). Defaults to 'left' */
  sidebarPosition?: 'left' | 'right';
  /** Controls position of the vertical tab navigation strip inside the sidebar relative to tab content ('left' | 'right'). Defaults to 'left' */
  tabNavigationPosition?: 'left' | 'right';
  tabsPosition?: 'left' | 'right';
  /** Primary UI theme color hex/string. Defaults to '#ea580c' (orange). Supports any valid CSS color. */
  themeColor?: string;
  /** Alias for themeColor */
  primaryColor?: string;
  /** Controls skeleton loading state in Tables tab */
  isTablesLoading?: boolean;
  tablesLoading?: boolean;
  /** Controls skeleton loading state in Placeholders tab */
  isPlaceholdersLoading?: boolean;
  placeholdersLoading?: boolean;
  customButtonStyles?: Record<string, React.CSSProperties>;
  customButtonClassNames?: Record<string, string>;
  customActionComponents?: {
    importHtml?: (props: { onClick: () => void }) => React.ReactNode;
    importPdf?: (props: { onClick: () => void }) => React.ReactNode;
    preview?: (props: { onClick: () => void }) => React.ReactNode;
    exportPdf?: (props: { onClick: () => void }) => React.ReactNode;
    export?: (props: { onClick: () => void }) => React.ReactNode;
    dummyDataPreview?: (props: { onClick: () => void; isApplied: boolean }) => React.ReactNode;
  };
  /** Optional custom data-tour attribute selectors passed from parent project for onboarding tutorials */
  tourSelectors?: TourSelectors;
  importedHtml?: string;
}
```

| Prop | Type | Default | Details |
| :--- | :--- | :--- | :--- |
| `tabNavigationPosition` / `tabsPosition` | `'left' \| 'right'` | `'left'` | Controls the position of the vertical navigation tab bar strip relative to the tab content panel inside the sidebar (`'left'` or `'right'`). |
| `sidebarPosition` | `'left' \| 'right'` | `'left'` | Controls the position of the entire sidebar panel relative to the canvas (`'left'` or `'right'`). |
| `dummyData` | `DummyData` | `undefined` | Map of dynamic sample key-values (`{ placeholders: { "carrier_code": "DHL", "sender.name": "BEO Software" } }`) to replace placeholders in text, tables, and images. |
| `showDummyDataPreview` | `boolean` | `true` | Controls visibility of the **"View Dummy Data"** action button in the canvas toolbar. |
| `onToggleDummyDataPreview` | `(isApplied: boolean) => void` | `undefined` | Callback fired when the user toggles the View Dummy Data preview button on/off. |
| `getHTMLOutput` | `(html: string) => void` | `undefined` | Real-time callback prop to receive or retrieve the latest compiled template HTML code on demand / changes. |
| `themeColor` / `primaryColor` | `string` | `'#ea580c'` | Configures the primary theme color for the entire editor UI (buttons, active tabs, selected block outlines, range sliders, toggles, badges, drag lines). Accepts any valid hex (`#3b82f6`), RGB (`rgb(59, 130, 246)`), or named color (`purple`, `blue`). |
| `showHeader` | `boolean` | `true` | Controls visibility of the top header toolbar. |
| `tourSelectors` | `TourSelectors` | `undefined` | Optional prop interface to pass custom `data-tour` attribute names to editor elements for driver tours (`sidebar`, `tabText`, `tabTables`, `tableDragHandle`, `placeholderSearch`, etc.). |
| `templatingLanguage` | `'js' \| 'ts' \| 'handlebars' \| 'liquid' \| 'scriban' \| 'dotnet' \| 'csharp' \| 'custom'` | `'js'` | Configures loop-tag syntax mode for exported HTML tables. Supports JavaScript/TypeScript Template Literals (`js`/`ts`), Handlebars (`handlebars`), Liquid (`liquid`), Scriban (`scriban`), and C# Razor (`csharp`). |
| `tableSchemas` | `TableSchemaInfo[]` | `[]` | Configures dynamic table schemas. Supports top-level loop tables and nested sub-tables. |
| `placeholders` | `PlaceholderItem[]` | `[]` | Controls variables shown in the Placeholders tab. |
| `isTablesLoading` / `tablesLoading` | `boolean` | `false` | Displays skeleton loading state in the Tables tab panel. |
| `isPlaceholdersLoading` / `placeholdersLoading` | `boolean` | `false` | Displays skeleton loading state in the Placeholders tab panel. |
| `customButtonStyles` | `Record<string, React.CSSProperties>` | `undefined` | Inline style overrides for header action buttons (`importHtml`, `importPdf`, `clearCanvas`, `preview`, `export`, `exportPdf`, `dummyDataPreview`). |
| `customButtonClassNames` | `Record<string, string>` | `undefined` | Custom CSS class names to override button styles for header actions. |
| `customActionComponents` | `Object` | `undefined` | Custom renderer functions for header action buttons (`importHtml`, `importPdf`, `preview`, `exportPdf`, `export`, `dummyDataPreview`). |
| `defaultLogo` | `string` | Neutral SVG | Default image source for logo blocks. |
| `defaultBanner` | `string` | Neutral SVG | Default image source for banner blocks. |
| `headerTitle` | `string` | `'Layout Designer'` | Header title text displayed at top of editor. |
| `headerSubtitle` | `string` | `'Interactive Document HTML Builder'` | Header subtitle text. |
| `onExport` | `(html: string) => void` | `undefined` | Called when user exports template. |
| `onExportPdf` | `(html: string) => void` | `undefined` | Called when user downloads PDF. |
| `importedHtml` | `string` | `undefined` | Forcefully loads / parses the provided raw HTML template string in the editor on prop change. |

| Exported Helper Function | Parameters | Description |
| :--- | :--- | :--- |
| `mountHtmlEditor` | `(container: HTMLElement, props?: HtmlEditorProps)` | Mounts the full editor into any DOM element container. Perfect for Vue, Angular, Svelte, and Vanilla JS applications. |
| `unmountHtmlEditor` | `(container: HTMLElement)` | Unmounts the editor component and cleans up internal DOM nodes. |

---

## ⚡ Templating Language Output Comparison

### TypeScript / JavaScript ES6 Template Literals (`templatingLanguage="ts"` or `"js"`)
```html
<table>
  <thead>
    <tr>
      <th>SKU</th>
      <th>Product Name</th>
      <th>Price</th>
    </tr>
  </thead>
  <tbody>
    <!-- ${items.map(item => ` --><tr>
      <td>${item.sku}</td>
      <td>${item.name}</td>
      <td>${item.price}</td>
    </tr><!-- `).join('')} -->
  </tbody>
</table>
```

### Handlebars / Mustache (`templatingLanguage="handlebars"`)
```html
<table>
  <thead>
    <tr>
      <th>SKU</th>
      <th>Product Name</th>
      <th>Price</th>
    </tr>
  </thead>
  <tbody>
    <!-- {{#each items}} --><tr>
      <td>{{sku}}</td>
      <td>{{name}}</td>
      <td>{{price}}</td>
    </tr><!-- {{/each}} -->
  </tbody>
</table>
```

### C# / Razor (`templatingLanguage="csharp"`)
```html
<table>
  <thead>
    <tr>
      <th>SKU</th>
      <th>Product Name</th>
      <th>Price</th>
    </tr>
  </thead>
  <tbody>
    <!-- @foreach (var item in items) { --><tr>
      <td>@item.Sku</td>
      <td>@item.Name</td>
      <td>@item.Price</td>
    </tr><!-- } -->
  </tbody>
</table>
```

---

## 📄 License

Proprietary &amp; Commercial License © 2026 [BEO Software Pvt. Ltd.](https://beo-software.in/)

All rights reserved. Unauthorized copying, distribution, or commercial use is strictly prohibited. For licensing inquiries, please visit [beo-software.in](https://beo-software.in/).
