DraftJS Utils

0.10.2 · active · verified Sun Apr 19

DraftJS Utils is a collection of helper functions designed to simplify common operations when working with Facebook's Draft.js rich text editor framework. Currently at version 0.10.2, this library offers utilities for tasks such as retrieving selected content blocks, extracting plain text from selections, and manipulating editor state, often leveraging Immutable.js data structures (like OrderedMap and List) for its outputs, aligning with Draft.js's internal data model. While there isn't an explicit release cadence, updates are typically made as needed to support new Draft.js features or address community requirements, given its pre-1.0 versioning. Its key differentiators include providing pre-tested, battle-hardened functions for common Draft.js patterns, reducing boilerplate code, and helping developers interact more efficiently with `EditorState` and `ContentBlock` objects without needing to re-implement these functionalities.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to initialize an `EditorState` and use `draftjs-utils` to retrieve selected blocks and text, and apply a basic modification, highlighting the Immutable.js returns.

import { EditorState, ContentState, SelectionState } from 'draft-js';
import { getSelectedBlocksList, getSelectionText, removeSelectedBlocksStyle } from 'draftjs-utils';

// Create a basic EditorState for demonstration purposes.
// In a real application, EditorState would come from your Draft.js editor component.
const contentState = ContentState.createFromText('Hello world! This is a test paragraph.');
const selectionState = SelectionState.createEmpty(contentState.getFirstBlock().getKey())
  .merge({
    anchorKey: contentState.getFirstBlock().getKey(),
    anchorOffset: 6,
    focusKey: contentState.getFirstBlock().getKey(),
    focusOffset: 11,
    isBackward: false,
    hasFocus: true
  });
const editorState = EditorState.forceSelection(EditorState.createWithContent(contentState), selectionState);

console.log('--- Using draftjs-utils ---');

// 1. Get selected blocks as an Immutable.List
const selectedBlocks = getSelectedBlocksList(editorState);
console.log('Selected Blocks Count:', selectedBlocks.size);
selectedBlocks.forEach((block, index) => {
  console.log(`Block ${index + 1} Text: "${block.getText()}"`);
});

// 2. Get selected text as a plain string
const selectedText = getSelectionText(editorState);
console.log('Selected Text:', `"${selectedText}"`);

// 3. Example of a modification utility: remove style from selected blocks
// This returns a new EditorState which you would then set in your Draft.js editor.
const newEditorState = removeSelectedBlocksStyle(editorState);
console.log('EditorState modified?', newEditorState !== editorState);

view raw JSON →