editorjs

How to load blocks data into EditorJS?


I want to load blocks data dynamically to my EditorJS instance. I would like to do something like this:

const editor = new EditorJS();
editor.load({ blocks: my_blocks })

I do not seem to find any documentation on how to do it on https://editorjs.io/

I know that I can load blocks to EditorJS during initialization, but I need to load dynamic data on button click.


Solution

  • You could use the Blocks Core API, by means of the insert() method, using the below signature:

     insert(type?: string, data?: BlockToolData, config?: ToolConfig, index?: number, needToFocus?: boolean): void
    

    So, in your case, it could be:

    editor.blocks.insert('header', {text: 'My header'});
    

    Where header is the type and the second argument is the block data

    A cleaner approach would be to pre-define your block as follows:

    const blockToAdd = {
      type: 'header', 
      data: {
         text: 'My header'
      }
    };
    
    editor.blocks.insert(blockToAdd);