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.
2 replies on “How to Listen for Changes in a contentEditable Element in React?”
You save my life!
I’ve been looking for this solution for months.
Thanks so much!!
Thanks for reading.