Convert Figma logo to code with AI

facebookarchive logodraft-js

A React framework for building text editors.

22,572
2,635
22,572
955

Top Related Projects

19,096

Lexical is an extensible text editor framework that provides excellent reliability, accessibility and performance.

43,060

Quill is a modern WYSIWYG editor built for compatibility and extensibility

29,602

A completely customizable framework for building rich text editors. (Currently in beta.)

14,837

The world's #1 JavaScript library for rich text editing. Available for React, Vue and Angular

Powerful rich text editor framework with a modular architecture, modern integrations, and features like collaborative editing.

18,951

A rich text editor for everyday writing

Quick Overview

Draft.js is a rich text editor framework for React, developed by Facebook. It provides a flexible and customizable foundation for building text editors with features like rich styling, entity support, and immutable model architecture.

Pros

  • Highly customizable and extensible
  • Built on React, integrating seamlessly with React applications
  • Immutable data model for efficient updates and undo/redo functionality
  • Strong community support and ecosystem of plugins

Cons

  • Steep learning curve for beginners
  • Limited built-in features compared to some other rich text editors
  • Performance can be an issue with large documents
  • Lack of official mobile support

Code Examples

  1. Creating a basic editor:
import React from 'react';
import { Editor, EditorState } from 'draft-js';

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

  return <Editor editorState={editorState} onChange={setEditorState} />;
}
  1. Applying inline styles:
import { RichUtils } from 'draft-js';

// Inside your component
const handleBoldClick = () => {
  setEditorState(RichUtils.toggleInlineStyle(editorState, 'BOLD'));
};
  1. Adding entities (e.g., links):
import { EditorState, RichUtils, Entity } from 'draft-js';

// Inside your component
const addLink = (url) => {
  const contentState = editorState.getCurrentContent();
  const contentStateWithEntity = contentState.createEntity(
    'LINK',
    'MUTABLE',
    { url }
  );
  const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
  const newEditorState = EditorState.set(editorState, {
    currentContent: contentStateWithEntity
  });
  setEditorState(RichUtils.toggleLink(
    newEditorState,
    newEditorState.getSelection(),
    entityKey
  ));
};

Getting Started

To start using Draft.js in your React project:

  1. Install Draft.js:

    npm install draft-js react react-dom
    
  2. Import and use the Editor component:

    import React, { useState } from 'react';
    import { Editor, EditorState } from 'draft-js';
    import 'draft-js/dist/Draft.css';
    
    function MyEditor() {
      const [editorState, setEditorState] = useState(EditorState.createEmpty());
    
      return (
        <div>
          <Editor editorState={editorState} onChange={setEditorState} />
        </div>
      );
    }
    
    export default MyEditor;
    
  3. Customize the editor by adding controls, styling, and additional functionality as needed.

Competitor Comparisons

19,096

Lexical is an extensible text editor framework that provides excellent reliability, accessibility and performance.

Pros of Lexical

  • More modern architecture with better performance and smaller bundle size
  • Improved collaborative editing support
  • Easier to extend and customize with a plugin-based system

Cons of Lexical

  • Newer project with less community support and fewer resources available
  • Steeper learning curve for developers familiar with Draft.js
  • Some features still in development or not as mature as Draft.js equivalents

Code Comparison

Draft.js:

import { Editor, EditorState } from 'draft-js';

const [editorState, setEditorState] = useState(EditorState.createEmpty());

<Editor editorState={editorState} onChange={setEditorState} />

Lexical:

import { LexicalComposer } from '@lexical/react/LexicalComposer';
import { PlainTextPlugin } from '@lexical/react/LexicalPlainTextPlugin';

<LexicalComposer initialConfig={editorConfig}>
  <PlainTextPlugin contentEditable={<ContentEditable />} placeholder={<div>Enter some text...</div>} />
</LexicalComposer>

Summary

Lexical is a more modern and performant alternative to Draft.js, offering improved collaborative editing and extensibility. However, it's a newer project with less community support and a steeper learning curve. The code structure differs significantly, with Lexical using a more component-based approach compared to Draft.js's state management style.

43,060

Quill is a modern WYSIWYG editor built for compatibility and extensibility

Pros of Quill

  • Lightweight and easy to set up
  • Rich set of built-in modules and formats
  • Better cross-browser compatibility

Cons of Quill

  • Less flexible for complex customizations
  • Smaller community and ecosystem compared to Draft.js
  • Limited support for collaborative editing

Code Comparison

Draft.js:

import { Editor, EditorState } from 'draft-js';

const [editorState, setEditorState] = useState(EditorState.createEmpty());

<Editor editorState={editorState} onChange={setEditorState} />

Quill:

import Quill from 'quill';

const quill = new Quill('#editor', {
  theme: 'snow'
});

Draft.js uses a more React-centric approach with state management, while Quill offers a simpler API for initialization. Draft.js provides greater control over the editing experience but requires more setup. Quill, on the other hand, comes with a pre-configured set of features that are easier to implement out of the box.

Both libraries have their strengths, with Draft.js excelling in flexibility and customization, and Quill offering a more straightforward implementation for common use cases. The choice between them depends on the specific requirements of your project and the level of control you need over the editing experience.

29,602

A completely customizable framework for building rich text editors. (Currently in beta.)

Pros of Slate

  • More flexible and customizable architecture
  • Better support for complex document structures
  • Easier to extend with plugins and custom behaviors

Cons of Slate

  • Steeper learning curve due to its more abstract model
  • Smaller community and ecosystem compared to Draft.js
  • Less mature, potentially more bugs and breaking changes

Code Comparison

Draft.js example:

const editorState = EditorState.createWithContent(contentState);
<Editor editorState={editorState} onChange={this.onChange} />

Slate example:

const editor = useMemo(() => withReact(createEditor()), []);
<Slate editor={editor} value={initialValue} onChange={value => setValue(value)}>
  <Editable />
</Slate>

Both Draft.js and Slate are popular rich text editing frameworks for React applications. Draft.js, developed by Facebook, offers a more opinionated and structured approach, while Slate provides a more flexible and customizable solution. Draft.js has a larger community and more extensive documentation, making it easier for beginners to get started. However, Slate's plugin-based architecture and support for complex document structures make it more suitable for advanced use cases and highly customized editing experiences. The choice between the two depends on the specific requirements of your project and the level of customization needed.

14,837

The world's #1 JavaScript library for rich text editing. Available for React, Vue and Angular

Pros of TinyMCE

  • More mature and feature-rich, with a wider range of plugins and customization options
  • Better support for traditional WYSIWYG editing, including tables and advanced formatting
  • Easier integration with existing HTML content and workflows

Cons of TinyMCE

  • Larger file size and potentially slower performance, especially for simpler use cases
  • Less flexibility for building custom editing experiences or content structures
  • Steeper learning curve for developers due to its extensive API and configuration options

Code Comparison

TinyMCE initialization:

tinymce.init({
  selector: '#myTextarea',
  plugins: 'link image table',
  toolbar: 'undo redo | formatselect | bold italic | alignleft aligncenter alignright'
});

Draft.js initialization:

const editorState = EditorState.createEmpty();
<Editor
  editorState={editorState}
  onChange={this.onChange}
  placeholder="Enter some text..."
/>

TinyMCE focuses on providing a ready-to-use editor with extensive features, while Draft.js offers a more flexible foundation for building custom editors. TinyMCE is better suited for traditional rich text editing, whereas Draft.js excels in creating tailored editing experiences within React applications.

Powerful rich text editor framework with a modular architecture, modern integrations, and features like collaborative editing.

Pros of CKEditor 5

  • More feature-rich out-of-the-box, with a wide range of plugins and customization options
  • Better support for collaborative editing and real-time collaboration
  • Stronger focus on accessibility and compliance with WCAG 2.1 standards

Cons of CKEditor 5

  • Steeper learning curve due to its more complex architecture
  • Larger bundle size, which may impact load times for web applications
  • Less flexibility for custom data models compared to Draft.js

Code Comparison

CKEditor 5:

import ClassicEditor from '@ckeditor/ckeditor5-build-classic';

ClassicEditor
    .create(document.querySelector('#editor'))
    .then(editor => {
        console.log('Editor was initialized', editor);
    })
    .catch(error => {
        console.error(error);
    });

Draft.js:

import React from 'react';
import { Editor, EditorState } from 'draft-js';

function MyEditor() {
    const [editorState, setEditorState] = React.useState(EditorState.createEmpty());
    return <Editor editorState={editorState} onChange={setEditorState} />;
}

Both CKEditor 5 and Draft.js are powerful rich text editing solutions, but they cater to different needs. CKEditor 5 offers a more complete package with extensive features, while Draft.js provides a flexible foundation for building custom editors. The choice between them depends on the specific requirements of your project.

18,951

A rich text editor for everyday writing

Pros of Trix

  • Simpler API and easier to integrate into existing projects
  • Built-in toolbar and formatting options out of the box
  • Lightweight and doesn't require React as a dependency

Cons of Trix

  • Less flexibility for custom implementations and advanced features
  • Smaller community and ecosystem compared to Draft.js
  • Limited support for complex content structures (e.g., nested blocks)

Code Comparison

Trix:

<trix-editor class="trix-content"></trix-editor>

document.addEventListener("trix-initialize", function(event) {
  var editor = event.target.editor;
  editor.insertString("Hello, Trix!");
});

Draft.js:

import { Editor, EditorState } from 'draft-js';

const [editorState, setEditorState] = useState(EditorState.createEmpty());

<Editor editorState={editorState} onChange={setEditorState} />

Both Trix and Draft.js are popular rich text editors, but they cater to different use cases. Trix offers a more straightforward implementation with built-in features, making it ideal for projects that need a quick and easy solution. Draft.js, on the other hand, provides greater flexibility and customization options, making it suitable for complex editing requirements and React-based applications. The choice between the two depends on the specific needs of your project and the level of control you require over the editing experience.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

draftjs-logo

Draft.js

Build Status npm version

Live Demo


Status

THIS PROJECT IS CURRENTLY IN MAINTENANCE MODE. It will not receive any feature updates, only critical security bug patches. On 31st December 2022 the repo will be fully archived.

For users looking for an open source alternative, Meta have been working on migrating to a new framework, called Lexical. It's still experimental, and we're working on adding migration guides, but, we believe, it provides a more performant and accessible alternative.


Draft.js is a JavaScript rich text editor framework, built for React and backed by an immutable model.

  • Extensible and Customizable: We provide the building blocks to enable the creation of a broad variety of rich text composition experiences, from basic text styles to embedded media.
  • Declarative Rich Text: Draft.js fits seamlessly into React applications, abstracting away the details of rendering, selection, and input behavior with a familiar declarative API.
  • Immutable Editor State: The Draft.js model is built with immutable-js, offering an API with functional state updates and aggressively leveraging data persistence for scalable memory usage.

Learn how to use Draft.js in your own project.

Draft.js is used in production on Facebook, including status and comment inputs, Notes, and messenger.com.

API Notice

Before getting started, please be aware that we recently changed the API of Entity storage in Draft.

Previously, the old API was set to be removed in v0.11.0. Since, the plans have changed— v0.11.0 still supports the old API and v0.12.0 will remove it. Refer to the docs for more information and information on how to migrate.

Getting Started

npm install --save draft-js react react-dom

or

yarn add draft-js react react-dom

Draft.js depends on React and React DOM which must also be installed.

Using Draft.js

import React from 'react';
import ReactDOM from 'react-dom';
import {Editor, EditorState} from 'draft-js';

function MyEditor() {

  
  constructor(props) {
    super(props);
    this.state = {editorState: EditorState.createEmpty()};
    this.onChange = (editorState) => this.setState({editorState});
    this.setEditor = (editor) => {
      this.editor = editor;
    };
    this.focusEditor = () => {
      if (this.editor) {
        this.editor.focus();
      }
    };
  }

  componentDidMount() {
    this.focusEditor();
  }

  render() {
    return (
      <div style={styles.editor} onClick={this.focusEditor}>
        <Editor
          ref={this.setEditor}
          editorState={this.state.editorState}
          onChange={this.onChange}
        />
      </div>
    );
  }
}

const styles = {
  editor: {
    border: '1px solid gray',
    minHeight: '6em'
  }
};

ReactDOM.render(
  <MyEditor />,
  document.getElementById('container')
);

Since the release of React 16.8, you can use Hooks as a way to work with EditorState without using a class.

import React from "react";
import { Editor, EditorState } from "draft-js";
import "draft-js/dist/Draft.css";

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

  const editor = React.useRef(null);
  function focusEditor() {
    editor.current.focus();
  }

  return (
    <div
      style={{ border: "1px solid black", minHeight: "6em", cursor: "text" }}
      onClick={focusEditor}
    >
      <Editor
        ref={editor}
        editorState={editorState}
        onChange={setEditorState}
        placeholder="Write something!"
      />
    </div>
  );
}

Note that the editor itself is only as tall as its contents. In order to give users a visual cue, we recommend setting a border and a minimum height via the .DraftEditor-root CSS selector, or using a wrapper div like in the above example.

Because Draft.js supports unicode, you must have the following meta tag in the <head> </head> block of your HTML file:

<meta charset="utf-8" />

Further examples of how Draft.js can be used are provided in the /examples directory of this repo.

Building Draft.js

Draft.js is built with Yarn v1. Using other package managers mgiht work, but is not officially supported.

To clone and build, run:

git clone https://github.com/facebook/draft-js.git
cd draft-js
yarn install
yarn run build

Examples

To run the examples in the /examples directory, first build Draft.js locally as described above. Then, open the example HTML files in your browser.

Browser Support

IE / Edge
IE / Edge
Firefox
Firefox
Chrome
Chrome
Safari
Safari
iOS Safari
iOS Safari
Chrome for Android
Chrome for Android
IE11, Edge [1, 2]last 2 versionslast 2 versionslast 2 versionsnot fully supported [3]not fully supported [3]

[1] May need a shim or a polyfill for some syntax used in Draft.js (docs).

[2] IME inputs have known issues in these browsers, especially Korean (docs).

[3] There are known issues with mobile browsers, especially on Android (docs).

Resources and Ecosystem

Check out this curated list of articles and open-sourced projects/utilities: Awesome Draft-JS.

Discussion and Support

Join our Slack team!

Contribute

We welcome pull requests. Learn how to contribute.

License

Draft.js is MIT licensed.

Examples provided in this repository and in the documentation are separately licensed.

NPM DownloadsLast 30 Days