Someone has made a project on NPM with my solution: react-contenteditable
I've encountered another problem that occurs when the browser tries to "reformat" the HTML you just gave it, leading to component always rerendering. See this.
Here's my production contentEditable implementation. It has some additional options over react-contenteditable
that you might want, including:
- locking
- imperative API allowing to embed HTML fragments
- ability to reformat the content
Summary:
FakeRainBrigand's solution has worked quite fine for me for some time until I got new problems. ContentEditables are a pain, and are not really easy to deal with React...
This JSFiddle demonstrates the problem.
As you can see, when you type some characters and click on Clear, the content is not cleared. This is because we try to reset the contenteditable to the last known virtual DOM value.
So it seems that:
- You need
shouldComponentUpdate
to prevent caret position jumps
- You can't rely on React's VDOM diffing algorithm if you use
shouldComponentUpdate
this way.
So you need an extra line, so that whenever shouldComponentUpdate
returns 'yes', you are sure the DOM content is actually updated.
So the version here adds a componentDidUpdate
and becomes:
var ContentEditable = React.createClass({
render: function(){
return <div id="contenteditable"
onInput={this.emitChange}
onBlur={this.emitChange}
contentEditable
dangerouslySetInnerHTML={{__html: this.props.html}}></div>;
},
shouldComponentUpdate: function(nextProps){
return nextProps.html !== this.getDOMNode().innerHTML;
},
componentDidUpdate: function() {
if (this.props.html !== this.getDOMNode().innerHTML) {
this.getDOMNode().innerHTML = this.props.html;
}
},
emitChange: function() {
var html = this.getDOMNode().innerHTML;
if (this.props.onChange && html !== this.lastHtml) {
this.props.onChange({
target: {
value: html
}
});
}
this.lastHtml = html;
}
});
The virtual DOM stays outdated, and it may not be the most efficient code, but at least it does work :) My bug is resolved
Details:
If you put shouldComponentUpdate to avoid caret jumps, then the contenteditable never rerenders (at least on keystrokes)
If the component never rerenders on key stroke, then React keeps an outdated virtual DOM for this contenteditable.
If React keeps an outdated version of the contenteditable in its virtual DOM tree, then if you try to reset the contenteditable to the value outdated in the virtual DOM, then during the virtual DOM diff, React will compute that there are no changes to apply to the DOM!
This happens mostly when:
- you have an empty contenteditable initially (shouldComponentUpdate=true,prop="",previous vdom=N/A),
- the user types some text and you prevent renderings (shouldComponentUpdate=false,prop=text,previous vdom="")
- after user clicks a validation button, you want to empty that field (shouldComponentUpdate=false,prop="",previous vdom="")
- as both the newly produced and old virtual DOM are "", React does not touch the DOM.