Categories
JavaScript Answers

How to add onChange event for contentEditable elements with React?

Spread the love

Sometimes, we want to add onChange event for contentEditable elements with React.

In this article, we’ll look at how to add onChange event for contentEditable elements with React.

How to add onChange event for contentEditable elements with React?

To add onChange event for contentEditable elements with React, we can listen to the input event on the contentEditable elements.

For instance, we write

<div
  contentEditable="true"
  onInput={(e) => console.log(e.currentTarget.textContent)}
>
  Text inside div
</div>

to add a contentEditable div into our component.

We listen for changes to its contents by setting onInput to a function that runs when the content changes.

Then we get the latest content of the div with e.currentTarget.textContent.

Conclusion

To add onChange event for contentEditable elements with React, we can listen to the input event on the contentEditable elements.

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 *