Registry / web-framework / react-contenteditable

react-contenteditable

JSON →
library3.3.7jsnpmunverified

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.

npm install react-contenteditable
INSTALL
IMPORT
SIG · REACT-CONTENTEDITA
R
react-contenteditable
web-frameworkjavascriptv3.3.7
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

ContentEditable
import ContentEditable from 'react-contenteditable'
import { ContentEditable } from 'react-contenteditable'
ContentEditable is exported as a default module. Avoid named import syntax.
ContentEditable
const ContentEditable = require('react-contenteditable')
const { ContentEditable } = require('react-contenteditable')
For CommonJS environments, use the direct require call as it's a default export.

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;
Debug
Known issues
gotchaUsing React's `useState` hook directly to manage the content of `<ContentEditable />` often leads to unexpected behavior, cursor jumping, or issues with input synchronization.
fix
Instead, utilize the `useRef` hook to store and update the editable content (e.g., `text.current = evt.target.value`), as this avoids unnecessary re-renders that interfere with native `contenteditable` behavior. The `html` prop should then receive `text.current`.
affects: >=1.0.0
gotchaWhen integrating `contenteditable` elements in React, you might encounter the console warning: 'Warning: A component is `contentEditable` and contains children managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated.'
fix
This warning indicates a conflict between React's virtual DOM and direct DOM mutations. If you are intentionally managing the content via the component's callbacks, you can suppress it by adding the prop `suppressContentEditableWarning={true}` to your `ContentEditable` component.
affects: >=1.0.0
breakingUnsanitized HTML input into `contenteditable` elements, particularly when using `dangerouslySetInnerHTML` (which `react-contenteditable` abstracts), poses a significant cross-site scripting (XSS) vulnerability. Attackers could embed malicious scripts.
fix
Always sanitize the HTML content before rendering or saving it. Libraries like 'sanitize-html' can be used to whitelist allowed HTML tags and attributes, both client-side on change and crucially, server-side before persisting data. The component's advanced example demonstrates sanitization.
affects: >=1.0.0
gotchaPasting rich text content directly into a `contenteditable` element often retains original formatting, leading to inconsistent styles or unwanted HTML tags being introduced, instead of plain text.
fix
Implement a paste handler (e.g., using `onPaste` prop) to process clipboard data, stripping formatting and inserting plain text or sanitized HTML. Refer to `contenteditable` best practices or the library's advanced examples for robust paste handling.
affects: >=1.0.0
Errors
Common errors & fixes
Warning: A component is contentEditable and contains children managed by React.
React warns about potential conflicts when its virtual DOM manages children within an element whose content can also be directly edited by the browser via `contenteditable`.
fix
If you are intentionally managing the content via `react-contenteditable`'s props, you can suppress this warning by adding `suppressContentEditableWarning={true}` to the `ContentEditable` component.
TypeError: Cannot read properties of null (reading 'current')
The `innerRef` property was accessed before it was properly assigned to a DOM element, often due to incorrect initialization or timing, especially with functional components.
fix
Ensure `innerRef` is initialized with `React.createRef()` in class components or `useRef(null)` in functional components, and that the ref is only accessed after the component has mounted (e.g., within `useEffect` with an empty dependency array or after render in class components).
Contenteditable doesn't work properly with React State (writes in the opposite way) / Cursor jumps to the end / Input state out of sync
Direct use of `useState` with `ContentEditable` causes frequent re-renders that interfere with the browser's native cursor positioning and input handling within the editable element.
fix
Refactor to use `useRef` to store the HTML content. Update `text.current` within the `onChange` handler and pass `text.current` to the `html` prop. The `ContentEditable` component will then manage the DOM updates more gracefully without triggering unwanted React re-renders for every keystroke.
Upgrade
Version history
3.3.7latest on npm
Audit
Dependencies
reactrequiredPeer dependency for React applications.
Agent activity
4 hits · last 30 days
node
4
Resources
react-contenteditable — npm install react-contenteditable · libregistry