DraftJS — Insert/Paste images into your content.

Dave Teu
3 min readMay 23, 2020

--

DraftJS is a text editor by the Facebook team that allows you to create content with rich text and media.

You can use DraftJS in the backend for your editorial team to create the latest articles or blog posts, or use in the front end for your users to write comments, create forum post etc.

It is highly customisable and you can read more about it here.

How is DraftJS comparable to other Text Editors?

There are plenty of text editors out there like Slate, Markdown, CKEditor (subscription payable) just to name a feel. All the editors have their pros and cons. These are some points you may have considered while choosing a text editor.

  • How they store the rich text containing media.(some in JSON, some in their own immutable state)
  • Different ways to display the created content because of the unique way they store their content.
  • Customisation level and difficulty of customisation.
  • Community support level (i’m all for open source).

I started out playing around with Slate because of how they manage their created content in JSON like format. This would mean I will be able to migrate easily if I were to switch to another text editor in the future.

However, Slate has not reached version 1. and is very unstable right now. Documentation is lacking and there are many different code examples out there that could be out dated and doesn’t work.

I gave up after spending few days setting up what I want.

DraftJS does look intimidating at first, but after spending a day working on it, I realise it’s not as difficult as it seems. Plenty of code example out there and their plugins are mostly stable. Notiably DraftJS WYSIWYG

Today I’m going to share with you what I have code-sourced to create, a paste image function for DraftJS!

I have tried many plugins and some are really hard to install and documentation is really lacking. It takes too much time to know exactly what those codes do to put them in production.

Let’s get started and write our own codes to enable Paste image in DraftJS.

These are the working installation steps provided by their website.

npm install draft-js react react-dom# or alternatelyyarn add draft-js react react-dom

Basic Usage

import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import {Editor, EditorState} from 'draft-js';
import 'draft-js/dist/Draft.css';
const myEditor = () => {
const [editorState, setEditorState] = useState(EditorState.createEmpty())
return ( <Editor
editorState={this.state.editorState}
onChange={this.onChange}
/>
)}

Now, we only need 2 functions to get the paste image functionality.

const handlePastedFiles = ( files) => {
const formData = new FormData();
formData.append('file',files[0])
fetch('/api/uploads',
{method: 'POST', body: formData})
.then(res => res.json())
.then(data => {
if (data.file) {
setEditorState(insertImage(data.file)) //created below
}
}).catch(err => {
console.log(err)
})
}
//DraftJS seems to have problem handling multiple files inserts, lets just try to work with 1 at the moment.

insertImage function that inserts the image into the DraftJS editor.

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

That’s it, just one function that handle the pasted image, and another function to insert into DraftJS.

Do note in handlePastedFiles, your API is suppose to return the URL of the uploaded file so insertImage can insert the image into your content.

Now we can call our editor to handle the pasted files.

<Editor 
editorState={this.state.editorState}
onChange={this.onChange}
handlePastedFiles={handlePastedFiles}
/>

I hope this simple code sharing will be a big step for your to creating your own functionalities for DraftJS.

In the next article, I will be sharing with you more codes I’ve learnt from DraftJS!

--

--

Dave Teu
Dave Teu

Responses (5)