Text Alignment in Draftjs — and use with draft-js-plugins toolbar

Ibraheems Ali
2 min readSep 13, 2021

--

Draftjs

Draft.js is a JavaScript framework for building rich text editors in React. Developed by the open-source team at Facebook, it allows you to build any type of rich text input, whether you’re only looking to support a few inline text styles or building a complex text editor for composing long-form articles

draft-js-plugins

High-quality plugins with great UX on top of DraftJS. so here we will talk about using the static-toolbar plugin.

Suppose we have the following app:

install draft-js & draft-js-plugins

npm install draft-js --save
npm install @draft-js-plugins/editor --save
npm install @draft-js-plugins/static-toolbar --save

The problem

So as you see in draft-js plugins, there are no options for Text Alignment, so it was the start point to found a solution for this issue.

The problem here is that we need to apply the alignment to block itself, not just for the span as the text color.

But what about using a specific block for every alignment?

The problem here is that I’m working on an editor for screenplay formatting, So I have previous blocks types such as Action, Dialogue, and Character.

The Solution

The main idea here is to give the block a default alignment which is left, so by using blockStyleFn.

<Editor
editorState={editorState}
onChange={onChange}
plugins={plugins}
blockStyleFn={blockStyleFn}
ref={editor}
/>

The second step is the function that applies the new style for the block and removes the previous styles.

now by using the draft-js-plugins toolbar, you can add your icon of left, right, and center alignment, here I used ant-design icons

Finally! as you see here we have new buttons for alignment.

--

--