React ContentEditable Component

3.3.7 · active · verified Sun Apr 19

react-contenteditable is a React component that simplifies the integration of the native `contenteditable` HTML attribute into React applications. It provides a controlled component approach, allowing developers to manage the `innerHTML` of an editable HTML element (like a `div` or `article`) via React state. The package, currently at version 3.3.7, addresses many common challenges associated with `contenteditable` in React, such as cursor jumping and state synchronization, often encountered when directly managing DOM mutations. It abstracts the use of `dangerouslySetInnerHTML`, providing a safer and more idiomatic React interface. While the component is designed to mitigate typical `contenteditable` pitfalls, users should be aware of inherent complexities like input sanitization to prevent XSS attacks and managing rich text pasting. The library ships with TypeScript types.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates a basic rich text editor using a class component, managing HTML content in state, and handling changes.

import React from 'react';
import ContentEditable from 'react-contenteditable';

class MyEditor extends React.Component {
  constructor() {
    super();
    this.contentEditable = React.createRef();
    this.state = { html: "<p><b>Hello</b> <i>World</i></p>" };
  }

  handleChange = (evt) => {
    this.setState({ html: evt.target.value });
  };

  // Optional: Sanitize content on blur to prevent XSS or unwanted formatting
  handleBlur = () => {
    console.log('Final content:', this.state.html);
    // In a real app, you might sanitize or save the content here
    // E.g., this.setState({ html: sanitizeHtml(this.state.html) });
  };

  render() {
    return (
      <ContentEditable
        innerRef={this.contentEditable}
        html={this.state.html} // innerHTML of the editable div
        disabled={false}      // use true to disable editing
        onChange={this.handleChange} // handle innerHTML change
        onBlur={this.handleBlur}
        tagName='article'     // Use a custom HTML tag (uses a div by default)
        suppressContentEditableWarning={true} // Suppress React's contentEditable warning
        style={{ border: '1px solid #ccc', minHeight: '100px', padding: '10px' }}
      />
    );
  }
}

export default MyEditor;

view raw JSON →