DraftJS Utils
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
-
TypeError: block.getText is not a function
cause Attempting to call Immutable.js `ContentBlock` methods on a plain JavaScript object or an incorrectly typed block.fixEnsure that the `block` variable is a valid `ContentBlock` instance returned by a `draftjs-utils` function, which are typically Immutable.js objects. Access methods using `block.get('text')` or ensure correct typing. -
TypeError: Cannot read properties of undefined (reading 'getSelection')
cause Passing `null` or `undefined` instead of a valid `EditorState` instance to a `draftjs-utils` function.fixAlways pass a properly initialized `EditorState` object to `draftjs-utils` functions. Verify that your `editorState` variable is not `null` or `undefined`. -
TypeError: Immutable.List.prototype.get not defined
cause This error or similar (e.g., for `OrderedMap`) indicates that you are trying to use an Immutable.js method on an object that is not an Immutable.js collection, possibly due to `immutable` version mismatch or incorrect usage.fixVerify that your `immutable` package version is compatible with both `draft-js` and `draftjs-utils`. Ensure the object you are calling `.get()` on is indeed an `Immutable.List` or `Immutable.OrderedMap` as expected by the utility's return type.
Warnings
- gotcha Many utility functions return Immutable.js data structures (e.g., `Immutable.List`, `Immutable.OrderedMap`), not plain JavaScript arrays or objects. Direct access via `[index]` or `.property` will fail; instead, use Immutable.js methods like `.get(index)` or `.map()`, `.forEach()`, etc.
- gotcha The peer dependency for `immutable` allows both `3.x.x` and `4.x.x`. `draft-js` itself often has a more specific `immutable` dependency. Mismatches between your `draft-js` and `draftjs-utils`'s effective `immutable` version can lead to subtle bugs or runtime errors due to different Immutable.js API behaviors or data structures.
- breaking As a pre-1.0 library (currently at 0.10.x), minor version increments (e.g., from 0.10.x to 0.11.x) may introduce breaking changes without adhering strictly to semantic versioning's major version bump rule. Always review the changelog when upgrading.
Install
-
npm install draftjs-utils -
yarn add draftjs-utils -
pnpm add draftjs-utils
Imports
- getSelectedBlocksList
const { getSelectedBlocksList } = require('draftjs-utils');import { getSelectedBlocksList } from 'draftjs-utils'; - getSelectionText
import getSelectionText from 'draftjs-utils';
import { getSelectionText } from 'draftjs-utils'; - removeSelectedBlocksStyle
import * as DraftUtils from 'draftjs-utils'; DraftUtils.removeSelectedBlocksStyle(...);
import { removeSelectedBlocksStyle } from 'draftjs-utils';
Quickstart
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);