npm package: @multocms/editorjs-renderer
Description: React component library for rendering EditorJS blocks with support for custom MultoCMS blocks
Author: MultoCMS
Latest version: 1.4.4

# @multocms/editorjs-renderer

React component library for rendering EditorJS blocks with support for custom MultoCMS blocks.

## ⚠️ Quick Setup for Tailwind Projects

**If your project already uses Tailwind CSS**, add this to your `tailwind.config.js`:

```js
content: [
  // ... your existing paths
  './node_modules/@multocms/editorjs-renderer/dist/**/*.{js,mjs}', // ⬅️ ADD THIS
]
```

**And install the Typography plugin** (required for `prose` classes):
```bash
npm install -D @tailwindcss/typography
```

Then add to `tailwind.config.js` plugins:
```js
plugins: [
  require('@tailwindcss/typography'), // ⬅️ ADD THIS
]
```

**Without this configuration, the component will have no styling!**

## Installation

```bash
npm install @multocms/editorjs-renderer
```

or

```bash
yarn add @multocms/editorjs-renderer
```

or

```bash
pnpm add @multocms/editorjs-renderer
```

## Quick Start

### 1. Import the component and styles

```tsx
import { BlockRenderer } from '@multocms/editorjs-renderer';
import '@multocms/editorjs-renderer/styles';

function MyComponent({ content }: { content: string }) {
  return <BlockRenderer content={content} />;
}
```

### 2. Configure Tailwind (REQUIRED)

Add the safelist to your `tailwind.config.js`:

```js
import { tailwindSafelist } from '@multocms/editorjs-renderer';

export default {
  content: [
    './app/**/*.{js,ts,jsx,tsx}',
    './components/**/*.{js,ts,jsx,tsx}',
  ],
  safelist: tailwindSafelist, // ⬅️ CRITICAL: Include this!
  theme: {
    extend: {},
  },
  plugins: [],
};
```

**⚠️ CRITICAL:** Without the safelist, buttons and dynamic classes won't work!

## Requirements

- React 18+

### Styling Requirements

**⚠️ Important:** This package uses Tailwind CSS utility classes for styling.

**If your project uses Tailwind CSS:**
- ✅ Works out of the box - no additional setup needed
- The component will use your project's Tailwind configuration

**If your project does NOT use Tailwind CSS:**
- ❌ You need to install and configure Tailwind CSS
- The component relies on Tailwind utility classes (e.g., `text-gray-700`, `mb-6`, `prose`)
- You cannot use this package without Tailwind CSS

### Tailwind CSS Configuration

**⚠️ Critical:** You must configure Tailwind to scan this package's files, otherwise the styles won't be included in your build!

**Step 1: Install Tailwind CSS (if not already installed)**
```bash
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
```

**Step 2: Update `tailwind.config.js`**

Add the package to your `content` array so Tailwind can scan it:

```js
/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    // Your existing paths
    './app/**/*.{js,ts,jsx,tsx,mdx}',
    './components/**/*.{js,ts,jsx,tsx,mdx}',
    
    // ⬇️ ADD THIS LINE - Required for @multocms/editorjs-renderer
    './node_modules/@multocms/editorjs-renderer/dist/**/*.{js,mjs}',
  ],
  theme: {
    extend: {},
  },
  plugins: [
    // If using @tailwindcss/typography for prose classes
    require('@tailwindcss/typography'),
  ],
}
```

**Step 3: Install Typography Plugin (if using `prose` classes)**

The component uses the `prose` class which requires the Tailwind Typography plugin:

```bash
npm install -D @tailwindcss/typography
```

Then add it to your `tailwind.config.js` plugins array (shown above).

**Why this is necessary:**
Tailwind CSS scans the files in your `content` array and only includes the utility classes it finds. Without scanning the package files, Tailwind won't know to include classes like `text-gray-700`, `mb-6`, `prose`, etc., and they won't be in your final CSS bundle.

## Quick Start

```tsx
import { BlockRenderer } from '@multocms/editorjs-renderer';

function MyComponent() {
  const editorJson = `{"blocks":[...]}`; // EditorJS JSON string
  
  return <BlockRenderer content={editorJson} />;
}
```

## Supported Blocks

### Standard EditorJS Blocks
- ✅ Paragraph
- ✅ Header (H1-H6)
- ✅ List (ordered/unordered)
- ✅ Checklist
- ✅ Quote
- ✅ Code
- ✅ Delimiter
- ✅ Warning
- ✅ Table
- ✅ Embed (YouTube, Twitter, Instagram, etc.)

### Custom MultoCMS Blocks
- ✅ **Image** - Enhanced image block with size selection, alignment, and caption
- ✅ **Media & Text** - Image with text side-by-side layout
- ✅ **Gallery** - Image gallery with lightbox support

## Usage

### Basic Usage

```tsx
import { BlockRenderer } from '@multocms/editorjs-renderer';

export default function PostContent({ content }: { content: string }) {
  return (
    <article className="max-w-4xl mx-auto">
      <BlockRenderer content={content} />
    </article>
  );
}
```

### With Configuration

```tsx
import { BlockRenderer } from '@multocms/editorjs-renderer';

<BlockRenderer
  content援editorJson}
  config={{
    imageBaseUrl: 'https://your-site.com',
    customStyles: {
      container: 'my-content-wrapper',
      paragraph: 'text-lg leading-relaxed',
      header: 'font-bold',
    },
  }}
/>
```

### With Next.js

```tsx
'use client';

import { BlockRenderer } from '@multocms/editorjs-renderer';

export default function Page({ params }: { params: { slug: string } }) {
  const [content, setContent] = useState<string>('');
  
  useEffect(() => {
    fetch(`/api/posts/${params.slug}`)
      .then(res => res.json())
      .then(data => setContent(data.content));
  }, [params.slug]);
  
  return <BlockRenderer content={content} />;
}
```

## Configuration Options

```typescript
interface BlockRendererConfig {
  /**
   * Base URL for resolving relative image URLs
   */
  imageBaseUrl?: string;
  
  /**
   * Custom CSS classes to apply to blocks
   */
  customStyles?: {
    container?: string;
    paragraph?: string;
    header?: string;
    list?: string;
    quote?: string;
    code?: string;
    image?: string;
    table?: string;
    gallery?: string;
    // ... other block types
  };
}
```

## Styling

The renderer uses Tailwind CSS utility classes by default. To customize:

1. **Override with custom classes** via `config.customStyles`
2. **Use CSS overrides** for global changes
3. **Configure Tailwind** in your project

### Example: Custom Tailwind Classes

```tsx
<BlockRenderer
  content={content}
  config={{
    customStyles: {
      container: 'prose prose-lg max-w-none',
      paragraph: 'text-gray-800 mb-4',
      header: 'text-3xl font-bold text-gray-900',
      gele: 'rounded-lg shadow-md',
    },
  }}
/>
```

## TypeScript

Full TypeScript support is included:

```tsx
import { BlockRenderer, BlockRendererProps, EditorJSBlock } from '@multocms/editorjs-renderer';

function MyComponent({ content }: { content: string }) {
  return <BlockRenderer content={content} />;
}
```

## Block Data Structure

The component expects EditorJS JSON format:

```json
{
  "blocks": [
    {
      "type": "paragraph",
      "data": {
        "text": "<p>Hello world</p>"
      }
    },
    {
      "type": "header",
      motivations": {
        "text": "My Header",
        "level": 2
      }
    },
    {
      "type": "image",
      "data": {
        "url": "https://example.com/image.jpg",
        "caption": "Image caption",
        "alignment": "center",
        "size": "large"
      }
    }
  ]
}
```

## Custom Blocks

### Image Block

Supports:
- Size variants (thumbnail, medium, large, full)
- Alignment (left, right, center, full)
- Caption
- Border and background options

### Media & Text Block

Supports:
- Image on left or right
- Vertical alignment (top, center, bottom)
- Responsive layout

### Gallery Block

Supports:
- Grid layout (2, 3, or 4 columns)
- Lightbox with keyboard navigation (Arrow keys, Escape)
- Image captions
- Click to view full size

### Columns Block

Supports:
- Two-column layouts with adjustable ratios:
  - 50% / 50% (equal columns)
  - 33% / 67% (narrow left, wide right)
  - 67% / 33% (wide left, narrow right)
- Full HTML/rich text content in both columns
- Text alignment support (left, center, right, justify)
- Responsive design - stacks vertically on mobile devices (< 768px)
- Supports all inline formatting (bold, italic, underline, links, etc.)

Example data structure:
```json
{
  "type": "columns",
  "data": {
    "leftColumn": "<p>Content for left column</p>",
    "rightColumn": "<p>Content for right column</p>",
    "columnRatio": "50-50"
  }
}
```

### Button Block

Supports:
- Custom button text and URL
- Link target (same window or new window)
- Tailwind CSS color options:
  - 9 background colors (blue, red, green, yellow, purple, pink, indigo, gray)
  - 4 text colors (white, black, dark gray, light gray)
  - 8 hover colors (darker shades)
- Center-aligned by default
- Fully responsive with hover effects

Example data structure:
```json
{
  "type": "button",
  "data": {
    "text": "Get Started",
    "url": "https://example.com/signup",
    "backgroundColor": "bg-blue-600",
    "textColor": "text-white",
    "hoverColor": "hover:bg-blue-700",
    "target": "_blank"
  }
}
```

## Troubleshooting

### Styles not appearing / Classes not working

**Problem:** Component renders but has no styling, or classes appear as plain text.

**Solution:** This means Tailwind isn't scanning the package files. 

1. Check your `tailwind.config.js` has:
   ```js
   content: [
     './node_modules/@multocms/editorjs-renderer/dist/**/*.{js,mjs}',
     // ... other paths
   ]
   ```

2. Restart your dev server after updating the config

3. Rebuild your CSS:
   ```bash
   # If using Next.js
   npm run dev
   
   # If using Vite
   npm run build
   ```

4. Verify Tailwind is scanning the package:
   - Check your build output for any warnings
   - The classes should appear in your generated CSS

### Images not loading
- Ensure `imageBaseUrl` is set correctly in config
- Check that image URLs are accessible
- Verify CORS settings if loading from external domains

### Styles not applying
- Ensure Tailwind CSS is configured in your project
- Check that custom classes are defined
- Verify `customStyles` prop is formatted correctly

### Unknown block types
- Check that the block type is supported
- Verify block data structure matches expected format
- Unknown blocks will log a warning and render nothing

## Changelog

### v1.4.0 (Latest)
- **NEW**: Support for Reusable Blocks and Block Sets
- Added `ReusableBlockComponent` for rendering reusable blocks
- Added `BlockSetComponent` for rendering multiple blocks as a set
- Reusable blocks can contain single blocks or multiple blocks grouped together
- Note: For standalone usage, pass `reusableBlockData` prop with the block data

### v1.3.3
- **FIX**: Removed inline styles and custom CSS - now uses ONLY Tailwind classes
- **NEW**: Exported `tailwindSafelist` for users to add to their Tailwind config
- Ensures button colors and dynamic classes work properly in consuming projects
- Updated documentation with Tailwind configuration instructions

### v1.3.1
- **FIX**: Added `!important` CSS rules to button styles to ensure they work in all contexts
- Buttons now render correctly regardless of surrounding CSS
- Package rebuilt and ready for publishing

### v1.3.0
- **NEW**: Button block for creating customizable call-to-action buttons
- Supports custom text, URL, and link target
- Tailwind CSS color options for background, text, and hover states
- Includes 9 background colors and 4 text colors
- Responsive and accessible

### v1.2.1
- **FIX**: Improved paste handling - now preserves HTML formatting when pasting into WYSIWYG editors
- **FIX**: Fixed Enter key behavior - creates paragraphs within editors instead of new blocks
- Enhanced documentation for Columns block

### v1.2.0
- **NEW**: Columns block for two-column layouts with adjustable ratios (50/50, 33/67, 67/33)
- Responsive design - columns stack on mobile devices
- Full WYSIWYG editing support in both columns
- Backward compatible with v1.1.x

### v1.1.0
- **NEW**: Full support for text alignment (left, center, right, justify) in paragraph blocks
- Added CSS styles to preserve inline `text-align` attributes
- Supports both Tailwind and standalone CSS usage
- Backward compatible with v1.0.x

### v1.0.3
- Initial stable release
- Support for all standard EditorJS blocks
- Custom MultoCMS blocks (Image, MediaText, Gallery)

## License

MIT

## Support

- Documentation: https://github.com/your-org/multocms
- Issues: https://github.com/your-org/multocms/issues