javascripthtmlreactjsinputcontenteditable

React contentEditable div with controlled input


Is there any way to have a controlled input contentEditable div?

I am looking for this exact behavior, but I need to use a contentEditable div instead of an input:

<input value={this.state.text}></input>

where the input doesn't show what is typed, but rather what is in this.state.text.

Just swapping out with a contentEditable div doesn't work, and it shows what is typed rather than what is in this.state.text:

<div contentEditable={true} value={this.state.text}></div>

Stackblitz: https://stackblitz.com/edit/react-q4xoya


Solution

  • Value is not a valid attribute for a div. It can be done, but is not officially supported and is certainly unorthodox.

    I suggest you change this line from your stackblitz:

    <div style={{border: '1px solid black'}} contentEditable={true} value={this.state.text}></div>
    

    to this:

    <div style={{border: '1px solid black'}} contentEditable={true}>{this.state.text}</div>