Skip to main content

Overview

The deleteBlock method removes a block from the editor and optionally focuses another block after deletion.

Signature

Blocks.deleteBlock(editor: YooEditor, options?: DeleteBlockOptions): void

Parameters

editor
YooEditor
required
The editor instance
options
DeleteBlockOptions
Configuration object for deleting the block

Examples

Basic Usage

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

// Delete current block
Blocks.deleteBlock(editor);

// Delete specific block by path
Blocks.deleteBlock(editor, { at: 3 });

// Delete specific block by ID
Blocks.deleteBlock(editor, { blockId: 'block-123' });

Delete Without Focusing

// Delete block without focusing another block
Blocks.deleteBlock(editor, {
  at: 3,
  focus: false,
});

Delete and Focus Next Block

// Delete current block and focus the next one
Blocks.deleteBlock(editor, {
  focusTarget: 'next',
});

Delete Multiple Blocks

const deleteMultipleBlocks = (editor: YooEditor, blockIds: string[]) => {
  blockIds.forEach((blockId) => {
    Blocks.deleteBlock(editor, {
      blockId,
      focus: false, // Don't focus during batch deletion
    });
  });
};

Use Cases

Delete Current Block

const deleteCurrentBlock = (editor: YooEditor) => {
  Blocks.deleteBlock(editor, {
    at: editor.path.current,
    focusTarget: 'previous',
  });
};

Delete Block with Validation

const safeDeleteBlock = (editor: YooEditor, blockId: string) => {
  const block = Blocks.getBlock(editor, { id: blockId });
  
  if (!block) {
    console.warn('Block not found');
    return;
  }

  // Check if it's safe to delete (e.g., not the only block)
  const allBlocks = Object.values(editor.children);
  if (allBlocks.length <= 1) {
    console.warn('Cannot delete the last block');
    return;
  }

  Blocks.deleteBlock(editor, { blockId });
};

Notes

The method automatically calls the plugin’s onDestroy lifecycle hook before deletion, allowing plugins to clean up resources.
If the block doesn’t exist (invalid at or blockId), the method will silently return without error.
Deleting a block is a destructive operation. There’s no built-in undo mechanism, so consider implementing your own undo/redo system if needed.
When focusTarget is 'previous' or 'next', the method will focus the target block at its last node point, allowing the user to continue editing seamlessly.

Type Definition

type DeleteBlockOptions = {
  at?: number; // YooptaPathIndex
  blockId?: string;
  focus?: boolean;
  focusTarget?: 'previous' | 'next' | 'none';
};