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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-11-22 11:00:00 +0000
Seen: 14 times
Last updated: Feb 09 '23
How can I display only the name and hide the button and text input box?
How can I load a text file in gensim?
How can I indent numerous lines of the HTML tag <p>?
How can I change the name of a subfolder within multiple folders by replacing a portion of the text?
How to arrange columns in a Flutter datatable?
How can the text size of the plot be enlarged using ggcuminc?
Does Sublime Text 3 consistently utilize tabs instead of spaces when indenting?
How to include Rmarkdown in an email for Microsoft Outlook, and make it visible?
How can I make the Vuetify Combobox return the id instead of the value?