Categories
React Answers

How to Detect Content Changes in contentEditable Elements in React?

Spread the love

Sometimes, we want to detect content changes in a contenteditable element in our React app.

In this article, we’ll look at how to detect content changes in a contenteditable element in our React app.

Detect Content Changes in contentEditable Elements in React

We can detect content changes in contenteditable elements by listening to the input event.

To do this, we write:

import React from "react";

export default function App() {
  return (
    <>
      <div
        contentEditable
        onInput={(e) => console.log(e.currentTarget.textContent)}
      >
        hello world
      </div>
    </>
  );
}

We pass in a function that logs the e.currentTarget.textContent property that has the text content of the div.

It’ll run as we change the content of the div by editing it.

Conclusion

We can detect content changes in contenteditable elements by listening to the input event.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *