Categories
React Answers

How to Listen for Changes in a contentEditable Element in React?

Spread the love

Sometimes, we want to listen for changes in a contentEditable element in React.

In this article, we’ll look at how to listen for changes in a contentEditable element in React.

Listen for Changes in a contentEditable Element in React

To listen for changes in a contentEditable element in React, we can listen to the input event on the div.

For instance, we write:

import React from "react";

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

to add a div with the contentEditable attribute set to true.

Then we add the onInput prop and pass in a function to log the content of the div, which is stored in the e.currentTarget.textContent property.

Now when we change the content of the div by typing, we see the latest div content logged in the console.

Conclusion

To listen for changes in a contentEditable element in React, we can listen to the input event on the div.

By John Au-Yeung

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

2 replies on “How to Listen for Changes in a contentEditable Element in React?”

Leave a Reply

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