Skip to main content

Overview

The getBlock method retrieves block data from the editor by block ID or path index.

Signature

Blocks.getBlock(editor: YooEditor, options: GetBlockOptions): YooptaBlockData | null

Parameters

editor
YooEditor
required
The editor instance
options
GetBlockOptions
required
Configuration object for retrieving the block

Return Value

Returns the YooptaBlockData object if found, or null if the block doesn’t exist.

Examples

Basic Usage

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

// Get block by ID
const block = Blocks.getBlock(editor, { id: 'block-123' });

if (block) {
  console.log('Block type:', block.type);
  console.log('Block order:', block.meta.order);
}

// Get block by path
const blockAtPath = Blocks.getBlock(editor, { at: 3 });

// Get current block
const currentBlock = Blocks.getBlock(editor, { at: editor.path.current });

Check Block Existence

const blockExists = (editor: YooEditor, blockId: string): boolean => {
  const block = Blocks.getBlock(editor, { id: blockId });
  return block !== null;
};

Get Block Properties

const getBlockInfo = (editor: YooEditor, blockId: string) => {
  const block = Blocks.getBlock(editor, { id: blockId });
  
  if (!block) {
    return null;
  }

  return {
    id: block.id,
    type: block.type,
    order: block.meta.order,
    depth: block.meta.depth,
    align: block.meta.align,
    hasContent: block.value.length > 0,
  };
};

Use Cases

Validate Before Operation

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

  Blocks.updateBlock(editor, blockId, newData);
};

Get All Block IDs

const getAllBlockIds = (editor: YooEditor): string[] => {
  return Object.keys(editor.children);
};

// Get all blocks with their data
const getAllBlocks = (editor: YooEditor) => {
  return Object.keys(editor.children).map((id) => 
    Blocks.getBlock(editor, { id })
  ).filter(Boolean);
};

Find Block by Type

const findBlocksByType = (editor: YooEditor, type: string) => {
  return Object.keys(editor.children)
    .map((id) => Blocks.getBlock(editor, { id }))
    .filter((block) => block?.type === type);
};

Notes

You must provide either at or id. If neither is provided, the method returns null.
The id parameter takes precedence over at if both are provided.
The at parameter uses the block’s meta.order property, not the array index. Make sure you’re using the correct order value.

Type Definition

type GetBlockOptions = {
  at?: number; // YooptaPathIndex
  id?: string;
};

type YooptaBlockData = {
  id: string;
  type: string;
  value: SlateElement[];
  meta: {
    order: number;
    depth: number;
    align?: 'left' | 'center' | 'right';
  };
};