Building a Rich Text Editor with React and Draft.js, Pt. 2.1: Text Highlighting

Siobhan Mahoney

This post is part of the second installment of a multi-part series about building a Rich Text Editor with React and Draft.js. For an introduction to the Draft.js framework with setup instructions, checkout Building a Rich Text Editor with Draft.js, Part 1: Basic Set Up. Links to additional posts in this series can be found below. The full codebase for my ongoing Draft.js project is available on GitHub. Feel free to checkout the deployed demo here.

After learning how to set up Draft.js and getting started with basic inline rich text tools, I became interested in exploring how to further leverage the framework’s wide range of features. In the next several posts, I will demonstrate how to power your React app with some of these rich text features, including instructions for integrating out-of-the-box plugins from the DraftJS Plugins catalogue and tutorials for building custom features. In this post, I will focus on how to build both a key command and button to toggle text highlighting.


Table of Contents:

I. Introduction to Draft.js Plugins

II. Text Highlight Key Command

III. Text Highlight UI Button


I. Introduction to DraftJS Plugins

To build the some of the features throughout this demo, we’ll be utilizing the DraftJS Plugins, which provides a plugin architecture for Draft.js. DraftJS Plugins serve as a wrapper that helps modularize functionality and facilitates the integrating rich text features.

The DraftJS Plugin package offers access to a number ready-to-use, out-of-the-box plugins power functionalities like alignment, word and character counters, emojis, and hashtags. Additionally, it enables the developer to build custom plugins.

To add DraftJS Plugins to a Draft.js project, run the following command:

yarn add draft-js-plugins-editor

Now, let’s highlight!

II. Highlight Text Feature Demo

To begin, let’s take a look at where we left off after the last post in this series, Building a Rich Text Editor with Draft.js, Part 1: Basic Set Up.

Following the example provided by Julian Krispel in his incredibly helpful demo, we’re going to be creating a key binding function that will highlight selected range of characters with the key combination command + h.

To begin, create a plugins directory to house custom plugin modules, and create file titled highlightPlugin.js.

Start your highlightPlugin.js file by importing Draft.js’ RichUtils library, which will allow for toggling inline styles.

import { RichUtils } from 'draft-js';

Next, build a function to create the plugin and define the CSS rules for highlighted text with customStyleMap prop:

export default () => {
return {
customStyleMap: {
‘HIGHLIGHT’: {
background: ‘#fffe0d’,
}
},

Next, define an editor command by calling the Draft.jskeyBindingFn callback prop and indicating that the key strokes command + h return the command arbitrarily titled 'highlight'.

  keyBindingFn: (e) => {
if (e.metaKey && e.key === 'h') {
return 'highlight';
}
}

If the keyBindingFn() returns 'highlight' , call the Draft.js callback handleKeyCommand, which allows you to map the command string to the RichUtils.toggleInlineStyle method, with the editorState as well as the name of our style 'HIGHLIGHT'.

handleKeyCommand: (command, editorState, { setEditorState }) => {
if (command === 'highlight') {
setEditorState(RichUtils.toggleInlineStyle(editorState, 'HIGHLIGHT'));
return true
}
},
}

Here’s how the finished highlightPlugin.js file should appear:

Next, prepare the PageContainer component by adding import Editor from 'draft-js-plugins-editor' to the list of module imports and removing Editor from the list of exports from 'draft.js'. You’ll also want to import highlightPlugin.

The updated import list should now be:

import React from "react"
import { EditorState, RichUtils } from "draft-js"
import Editor from "draft-js-plugins-editor"
import createHighlightPlugin from './plugins/highlightPlugin'

Generate the highlight plugin:

const highlightPlugin = createHighlightPlugin();

Update the PageContainer constructor method to define this.plugins and add highlightPlugin:

constructor(props) {
super(props);
this.state = {
editorState: EditorState.createEmpty()
};
this.plugins = [
highlightPlugin,
];

}

Finally, update the Editor component by passing it plugins as a prop:

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

And there you go!


III. Text Highlight UI Button

Now that our highlight key command is up and running, let’s make it easy for our users by providing a button to toggle highlights.

Within PageContainer.js, create onHighlight() , which will be passed to the click event handler attached to our new button. onHighlight() will simply call RichUtils.toggleInlineStyle, the method that conditionally defines our custom highlight key command, and similarly, pass it the current editorState and the 'HIGHLIGHT' command:

onHighlight = () => {
this.onChange(RichUtils.toggleInlineStyle(this.state.editorState, 'HIGHLIGHT'))
}

We’ll then create a <button> element in our render() function with an onClick event handler that calls onHighlight():

<button className="highlight" onClick={this.onHighlight}>
<span style={{ background: "yellow" }}>H</span>
</button>

Now with that in place, your editor should now be equipped with the highlight text functionality both through a key command and button!


Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade