Skip to main content

Overview

The duplicateBlock method creates an exact copy of a block and inserts it at a specified position.

Signature

Blocks.duplicateBlock(
  editor: YooEditor,
  options?: DuplicateBlockOptions
): string | undefined

Parameters

editor
YooEditor
required
The editor instance
options
DuplicateBlockOptions
Configuration object for duplicating

Return Value

Returns the ID of the newly created block, or undefined if duplication failed.

Examples

Basic Usage

import { Blocks } from '@yoopta/editor';

// Duplicate current block
const newBlockId = Blocks.duplicateBlock(editor);

// Duplicate specific block by path
const newBlockId = Blocks.duplicateBlock(editor, { at: 3 });

// Duplicate specific block by ID
const newBlockId = Blocks.duplicateBlock(editor, { blockId: 'block-123' });

Duplicate and Insert at Specific Position

// Duplicate and insert at beginning
const newBlockId = Blocks.duplicateBlock(editor, {
  at: 3,
  insertAt: 0,
});

// Duplicate and insert at end
const lastPosition = Object.keys(editor.children).length;
const newBlockId = Blocks.duplicateBlock(editor, {
  blockId: 'block-123',
  insertAt: lastPosition,
});

Duplicate with Custom Content

// Duplicate but with modified content
const newBlockId = Blocks.duplicateBlock(editor, {
  blockId: 'block-123',
  elements: editor.y('paragraph', {
    children: [editor.y.text('Modified duplicate')]
  }),
});

Use Cases

Duplicate Current Block

const duplicateCurrent = (editor: YooEditor) => {
  return Blocks.duplicateBlock(editor, {
    at: editor.path.current,
    focus: true,
  });
};

Duplicate Multiple Blocks

const duplicateMultiple = (editor: YooEditor, blockIds: string[]) => {
  const newBlockIds: string[] = [];
  
  blockIds.forEach((blockId) => {
    const newId = Blocks.duplicateBlock(editor, {
      blockId,
      focus: false,
    });
    if (newId) newBlockIds.push(newId);
  });
  
  return newBlockIds;
};

Notes

The duplicated block gets a new unique ID automatically. All other properties (type, value, meta) are copied from the original.
If insertAt is not provided, the duplicate is inserted right after the original block (at original.meta.order + 1).
The method performs a deep clone of the block data, so modifications to the duplicate won’t affect the original.
If the block doesn’t exist, the method returns undefined without error.

Type Definition

type DuplicateBlockOptions = {
  at?: number; // YooptaPathIndex
  blockId?: string;
  insertAt?: number; // YooptaPathIndex
  focus?: boolean;
  elements?: SlateElement;
};