Draft.js

0.11.7 · abandoned · verified Sun Apr 19

Draft.js is a JavaScript framework developed by Facebook for building rich text editors within React applications. It leverages an immutable data model, specifically `immutable-js`, to manage editor state, offering functional state updates and aggressive data persistence for scalable memory usage. The latest stable version is 0.11.7, released in August 2020. However, the project has since been formally archived by Facebook on GitHub in February 2023, making it read-only and indicating that it is no longer actively maintained. This means no further bug fixes, features, or security updates are expected. Key differentiators include its tight integration with React's declarative API for rendering, selection, and input behavior, and its extensible architecture allowing for a wide variety of rich text composition experiences, from basic styling to embedded media.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates a basic Draft.js editor using React Hooks, including state management, focusing, and handling basic key commands like bold/italic via RichUtils.

import React from 'react';
import ReactDOM from 'react-dom';
import { Editor, EditorState, RichUtils } from 'draft-js';
import 'draft-js/dist/Draft.css'; // Essential for basic styling

function MyEditor() {
  const [editorState, setEditorState] = React.useState(
    EditorState.createEmpty()
  );

  const editorRef = React.useRef(null);

  const focusEditor = () => {
    if (editorRef.current) {
      editorRef.current.focus();
    }
  };

  React.useEffect(() => {
    focusEditor();
  }, []);

  const handleKeyCommand = (command, editorState) => {
    const newState = RichUtils.handleKeyCommand(editorState, command);
    if (newState) {
      setEditorState(newState);
      return 'handled';
    }
    return 'not-handled';
  };

  return (
    <div style={{ border: '1px solid gray', minHeight: '6em', padding: '10px' }} onClick={focusEditor}>
      <Editor
        ref={editorRef}
        editorState={editorState}
        onChange={setEditorState}
        handleKeyCommand={handleKeyCommand}
        placeholder="Tell a story..."
      />
    </div>
  );
}

const container = document.getElementById('container');
if (container) {
  ReactDOM.render(<MyEditor />, container);
} else {
  console.warn("Element with ID 'container' not found. Quickstart code won't render.");
}

view raw JSON →