So I am trying to make an interaction which is similar to the file browser in VSCode. I display a list of items, and click on an item to select it. I want to then be able to press enter when an item is selected to make that item editable.
My first attempt was to use the contentEditable
property, as it seemed the easy way to turn editing on and off on my div:
...
render(
<div
contentEditable={this.state.isEditable}>
{this.state.text}
</div>
)
But when I use this method, I get this warning:
[Error] Warning: A component is
contentEditable
and containschildren
managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional.
If I understand correctly, contentEditable is breaking the convention of React, and this may cause issues if I use this method.
As I have read more about contentEditable
in general, I have also seen that there are some issues with the HTML generated inside being inconsistent across different browsers.
So my question is, what would be the standard/best practice to achieve something like this where I want to swap between a display-only element and an input element? Should I use an input tag instead and disable it instead of enabling it?
CodePudding user response:
You can consider using input's native attributes, readonly/disabled, depends on your use-case, for example:
<input readOnly={!this.state.isEditable}/>
CodePudding user response:
contenteditable
will give you HTML, but you're not using this.state.text
as HTML (just text), and as you've noted the HTML varies from browser to browser. I'd swap a styled input
for the div
:
return this.state.isEditable
? <input className="styling-class" type="text" value={this.state.text} />
: <div>{this.state.text}</div>
;