Ask Your Question
3

How can I use html-React to substitute specific text within a contentEditable div?

asked 2021-11-22 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-02-09 14:00:00 +0000

woof gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2021-11-22 11:00:00 +0000

Seen: 14 times

Last updated: Feb 09 '23