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-contenteditableVerified import paths — ran on the pinned version, not inferred.
Demonstrates a basic rich text editor using a class component, managing HTML content in state, and handling changes.
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`.
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.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.
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.
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.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).
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.