3

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

Makazau
  • 615
  • 7
  • 17
  • 1
    Try this in your stackblitz: `
    {this.state.text}
    `
    – Rob Moll Mar 27 '20 at 16:24
  • That displays `this.state.text` initially, but stops if typed in. I updated the stackblitz @RobMoll – Makazau Mar 27 '20 at 16:28
  • Yes. It changes if you type in the div, but not if you type in the input. Not sure what your intent is. – Rob Moll Mar 27 '20 at 16:30
  • My intent was for it to behave exactly like the input (I am just replacing some inputs with contenteditable divs because I need more control of styling and events). However, I think I should be able to make it work how I want by doing what you suggested and adding some extra events other places in my app. Thanks! – Makazau Mar 27 '20 at 16:33

1 Answers1

1

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>
Rob Moll
  • 3,345
  • 2
  • 9
  • 15
  • 1
    This doesn't make it behave exactly like the input, but it is probably the best option and I can make it work with some workarounds elsewhere. Thanks again! – Makazau Mar 27 '20 at 16:35