How to insert / upload image (update entity and blocks) in Draft.js?

狂风中的少年 提交于 2019-12-03 23:15:51

Took a while to figure out how to insert image.

  insertImage = (editorState, base64) => {
    const contentState = editorState.getCurrentContent();
    const contentStateWithEntity = contentState.createEntity(
      'image',
      'IMMUTABLE',
      { src: base64 },
    );
    const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
    const newEditorState = EditorState.set(
      editorState,
      { currentContent: contentStateWithEntity },
    );
    return AtomicBlockUtils.insertAtomicBlock(newEditorState, entityKey, ' ');
  };

Then you can use

const base64 = 'aValidBase64String';
const newEditorState = this.insertImage(this.state.editorState, base64);
this.setState({ editorState: newEditorState });

For render image, you can use Draft.js image plugin.

Live demo: codesandbox

The demo inserts a Twitter logo image.


If you want to insert a image from local file, you can try to use FileReader API to get that base64.

For how to get base64, it is simple, check

Live demo: jsbin

Now go ahead to put them together, you can upload image from local file!

If you want to insert a new Block then you probably would want to use ContentBlock and not mergeBlockData.

ContentBlock: https://draftjs.org/docs/api-reference-content-block.html#content

Please give this snippet a try.

import { genKey } from 'draft-js'

addNewBlock(editorState) {
  const text = 'Alpha';
  const block = new ContentBlock({
    key: genKey(),
    type: 'unstyled',
    text,
  });

  const contentState = editorState.getCurrentContent();
  const blockMap = contentState.getBlockMap().set(block.key, block);                   

  return EditorState.push(editorState, contentState.set('blockMap', blockMap));
}

If you are using draft-js image plugin, you can achieve this as follows.

Get the base64 of your image as @Hongbo Miao explained.

const imagePlugin = createImagePlugin();//initialize image plugin
const base64 = 'aValidBase64String';
const newEditorState = imagePlugin.addImage(this.state.editorState, base64);
this.setState({ editorState: newEditorState });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!