← All Insights

React-Draft-Wysiwyg: Adding a Find Text Option

React-Draft-Wysiwyg is a rich text editor built on Draft.js. Out of the box it does not include a find-text feature, but Draft.js gives you enough access to the underlying content state to build one yourself.

This post walks through adding a find dialog that searches all editor blocks and highlights every match with a yellow background using Draft.js inline styles.


Step 1: Build the Find Modal

The modal contains a text input and a search button. Using Grommet as the UI library, the structure looks like this:

import { Box, Button, Layer, TextInput } from 'grommet';

class FindTextModal extends React.Component {
  state = { findText: '' };

  onChangeFindText = e => {
    this.setState({ findText: e.target.value });
  };

  render() {
    return (
      <Layer onEsc={this.props.onClose}>
        <Box pad="medium" gap="small">
          <TextInput
            data-cy="find-text"
            autoFocus
            placeholder="Search..."
            onChange={this.onChangeFindText}
            value={this.state.findText}
          />
          <Button
            label="Find"
            onClick={() => this.props.onFind(this.state.findText)}
          />
        </Box>
      </Layer>
    );
  }
}

Step 2: Search and Highlight Logic

When the user clicks Find, the handler operates on the editor's content state. It converts the content to raw JS, iterates through each block, and uses a regex to find all character ranges that match the search text. It then applies a yellow background inline style to each match.

import { convertToRaw, Modifier, SelectionState, EditorState } from 'draft-js';

onFindClick = searchText => {
  const { editorState, onChange } = this.props;
  let contentState = editorState.getCurrentContent();
  const rawContent = convertToRaw(contentState);

  rawContent.blocks.forEach(block => {
    const text = block.text;
    const regex = new RegExp(searchText, 'gi');
    let match;

    while ((match = regex.exec(text)) !== null) {
      const start = match.index;
      const end = start + match[0].length;

      const blockSelection = SelectionState.createEmpty(block.key).merge({
        anchorOffset: start,
        focusOffset: end,
      });

      contentState = Modifier.applyInlineStyle(
        contentState,
        blockSelection,
        'HIGHLIGHT'
      );
    }
  });

  const newEditorState = EditorState.push(
    editorState,
    contentState,
    'change-inline-style'
  );

  onChange(newEditorState);
};

Step 3: Register the Custom Inline Style

Pass a customStyleMap to the editor so Draft.js knows how to render the HIGHLIGHT style:

const styleMap = {
  HIGHLIGHT: {
    backgroundColor: '#FFFF00',
  },
};

<Editor
  editorState={this.state.editorState}
  onEditorStateChange={this.onEditorStateChange}
  customStyleMap={styleMap}
/>

Result

When the user types a search term and clicks Find, every matching occurrence across all editor blocks is highlighted with a yellow background. The approach works on multi-block documents and is case-insensitive by default via the gi regex flags.

To clear highlights, push a new content state with the HIGHLIGHT style removed using Modifier.removeInlineStyle across the full document selection.