Draft-js: how to insert pictures in batches

Created on 22 Sep 2017  路  2Comments  路  Source: facebook/draft-js

addImages = (srcs, height, width, alt) => {
var self = this;
[].forEach.call(srcs,function (src, index) {
self.addImage(src, height, width, alt);
})
};

addImage = (src, height, width, alt) => {
    const {editorState, onChange, config} = this.props;
    const entityData = {src, height, width};
    if (config.alt.present) {
        entityData.alt = alt;
    }
    const entityKey = editorState
        .getCurrentContent()
        .createEntity('IMAGE', 'MUTABLE', entityData)
        .getLastCreatedEntityKey();

    const newEditorState = AtomicBlockUtils.insertAtomicBlock(
        editorState,
        entityKey,
        ' ',
    );
    onChange(newEditorState);
    this.doCollapse();
};

addImages(...)

just insert first image of srcs.

support

Most helpful comment

This is a working example:
https://jsfiddle.net/ut0q7x3n/1/

Hopefully that clears things up!

All 2 comments

Hmm - it makes sense to me that this doesn't work. My hunch is you need to wait to call onChange(newEditorState); until after all the images are inserted. Something like this could work:

// Adds all images and then triggers re-render with updated editorState
addImagesAndUpdate = (srcs, height, width, alt) => {
  var self = this;
  [].forEach.call(srcs,function (src, index) {
    self.addImage(src, height, width, alt);
  })
  onChange(newEditorState);
  this.doCollapse();
};

// Adds *one image* and then triggers re-render with updated editorState
addImageAndUpdate = (srcs, height, width, alt) => {
  var self = this;
  self.addImage(src, height, width, alt);
  onChange(newEditorState);
  this.doCollapse();
};

_addImage = (src, height, width, alt) => {
    const {editorState, onChange, config} = this.props;
    const entityData = {src, height, width};
    if (config.alt.present) {
        entityData.alt = alt;
    }
    const entityKey = editorState
        .getCurrentContent()
        .createEntity('IMAGE', 'MUTABLE', entityData)
        .getLastCreatedEntityKey();

    const newEditorState = AtomicBlockUtils.insertAtomicBlock(
        editorState,
        entityKey,
        ' ',
    );
};

I think it still needs polishing - let me see if I can come up with a working jsfiddle for you.

This is a working example:
https://jsfiddle.net/ut0q7x3n/1/

Hopefully that clears things up!

Was this page helpful?
0 / 5 - 0 ratings