I am trying to create a simple editor for writing a storyline. Right now I could show the html to markup in the editor where bold text are shown in bold and etc. I could also send the data in html form to server but I could not show the image in an editor and also could not upload the image in editor. I have created a codesandbox of it. Here is the link
https://codesandbox.io/s/5w4rp50qkp
The line of code is a bit huge. That is why I am posting the code in codesandbox where you can see the demo either.
Can anyone please help me to make this possible?
I originally posted my answer here
I copied it below for your convenience:
Took a while to figure out how to insert image after checking Draft.js source code.
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!