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.