You can use the onInput
event listener in combination with the setState()
method to update the content of a contentEditable
div with React. Here's an example:
class EditableDiv extends React.Component {
constructor(props) {
super(props);
this.state = {
content: this.props.content
};
}
handleInput = (e) => {
let updatedContent = e.target.innerHTML;
updatedContent = updatedContent.replace("old text", "new text");
this.setState({
content: updatedContent
});
}
render() {
return (
<div
contentEditable
dangerouslySetInnerHTML={{ __html: this.state.content }}
onInput={this.handleInput}
/>
);
}
}
ReactDOM.render(
<EditableDiv content="This is some old text." />,
document.getElementById("root")
);
In this example, we create a React component called EditableDiv
that takes in a content
prop which represents the initial content of the contentEditable
div. We initialize the component state with this prop in the constructor.
Inside the handleInput
method, we get the updated content from the contentEditable
div and use the replace()
method to substitute the text "old text" with "new text". We then update the component state with the updated content.
In the render()
method, we create a div
with the contentEditable
attribute set to true. We use the dangerouslySetInnerHTML
prop to set the initial HTML content of the div to the current value of the component state. We also set the onInput
event listener to call the handleInput
method whenever the content of the contentEditable
div changes.
This allows the user to edit the content of the contentEditable
div with React, and substitutes any instance of "old text" with "new text" as the user types.
Asked: 2021-11-22 11:00:00 +0000
Seen: 14 times
Last updated: Feb 09 '23