2

I am having trouble updating my image blocks in editorState in draft.js. I want to change atomic:image src on button save. So the src is for example now blob:http://localhost:3000/7661d307-871b-4039-b7dd-6efc2701b623 but I would like to update to src to for example /uploads-from-my-server/test.png

onSave(e) {
 e.preventDefault();
 const { editorState } = this.state;
 const contentState = editorState.getCurrentContent();

 editorState.getCurrentContent().getBlockMap().map((block) => {
  const type = block.getType();

  if (type === 'atomic:image') {
    const rangeToReplace = new SelectionState({
      anchorKey: block.getKey(),
      focusKey: block.getKey(),
    });

    Modifier.replaceText(contentState, rangeToReplace, '/uploads-from-my-server/test.png');
    const newContentState = editorState.getCurrentContent();
    this.setState({ editorState: newContentState });
  }

  return true;
});

I know I can access src string with block.getData().get('src') but I cant set though

Thank you for your awesome editor

jonjonson
  • 263
  • 2
  • 5
  • 16

1 Answers1

0

I was struggling with a similar problem, I ended up converting the content state to raw array using convertToRaw and then updating it manually and use convertFromRaw and set the new state :

import {EditorState, ContentState, convertToRaw, convertFromRaw /*, ...*/} from 'draft-js';

// ...

onSave(e) {
  e.preventDefault();
  const { editorState } = this.state;
  const contentState = editorState.getCurrentContent();

  let rawContent = convertToRaw(contentState);

  for(let i = 0; i < rawContent.blocks.length; i++) {
      let b = rawContent.blocks[i];
      if(b['type'] !== "unstyled" && b.entityRanges.length === 1) {
        const entityKey = b['entityRanges'][0]['key'];
        const entityMap = rawContent['entityMap'][entityKey];
        if(entityMap["type"] === "image") {
          rawContent['entityMap'][entityKey]['data']['src'] = '/uploads-from-my-server/test.png';         
        }
      }      
  } 

  const newContentState = convertFromRaw(rawContent);  
  const newEditorState = EditorState.push(this.state.editorState, newContentState, 'update-contentState');
  this.setState({editorState: newEditorState});
}

Note: This is not a fully working example, it's just a starting point. Hope it helps :)

Mohamed Ramrami
  • 12,026
  • 4
  • 33
  • 49