Editor.js: how to add new block programitically.

Created on 24 Aug 2019  路  3Comments  路  Source: codex-team/editor.js

i have blocks in json format i want to insert in editor programitically.

Most helpful comment

You can use data option in order to load your json data. It must be in the same format of EditorJS JSON output.

const editor = new EditorJS({
     tools: { 
        // Tools
     },
     data: YOUR JSON DATA
});

But if you want to insert extra block in current data, check insert mehod.

https://editorjs.io/blocks#insert

All 3 comments

You can use data option in order to load your json data. It must be in the same format of EditorJS JSON output.

const editor = new EditorJS({
     tools: { 
        // Tools
     },
     data: YOUR JSON DATA
});

But if you want to insert extra block in current data, check insert mehod.

https://editorjs.io/blocks#insert

I just tried insert method creating new Tool class like that :

class MyCustomBlocks {

  constructor({ data, api }){
     this.api = api;

     this.api.blocks.insert(
       "paragraph", { text : "1"}
    );

    this.api.blocks.insert(
      "paragraph", { text : "2"}
    );

   this.api.blocks.insert(
    "paragraph", { text : "3"}
    );
  }
}

const editor = new EditorJS({
     tools: { 

        // other tools

        mycustomblocks : MyCustomBlocks
     },
});

This creates 3 paragraph block in editor.

Altough the documentation points out that new block will be inserted after current block, the example code above inserts at the beginning of current blocks.

Parameters | Description
-- | --
String | New Block type
Object | New Block data
Object | Config for new Block's Tool
Number | Position for block. By default, it will inserted after current Block
Boolean | Need to set focus or not.

Be careful : This code inserts new blocks every refresh of page. You must set your logic.

thanks a lot

Was this page helpful?
0 / 5 - 0 ratings