4

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.

Damian
  • 1,084
  • 3
  • 14
  • 26
tzador
  • 2,535
  • 4
  • 31
  • 37

2 Answers2

4

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);
BiOS
  • 2,282
  • 3
  • 10
  • 24
  • 1
    Thank you, that should work. So I need to add the blocks manually one by one if I understood correctly. – tzador Feb 26 '21 at 10:51
  • Indeed, but you could create a function and provide an array of blocks as argument, as follows: `function addBlocks(blocks) { for (var i of blocks) { editor.blocks.insert(i) } }` – BiOS Feb 26 '21 at 10:55
  • Yes, of course. But we need to clean the existing blocks first. – tzador Feb 27 '21 at 05:45
  • I tried this way, but I got an error. You have to pass each property directly in the insert function as stated in https://stackoverflow.com/a/68949306/5199281 – tmsss Feb 14 '23 at 12:11
4

Not sure when this was added to the API, but there is also editor.render(data) which loads JSON data into the editor dynamically.

render(data: OutputData): Promise
Method removes all Blocks and fills with new passed JSON data

Source: https://editorjs.io/blocks#render

Tom
  • 471
  • 3
  • 11