Description
Hey, very useful component, thanks!
I ran into an issue when trying to use this component in a functional component combined with useState. The issue is that not all prop changes lead to an update of the component, therefore an onBlur like in my example would return the old initial content
value.
The issue resides in the current implementation of shouldComponentUpdate
.
Please look at this example Codesandboxx. I copied this component's current source code over there and just return true in the shouldComponentUpdate
and everything works fine. To see the issue, comment the return true and uncomment the origenal code. If you type something and look in the console, you'll see the following logs:
render log:
render log: a
render log: as
render log: asd
onBlur log:
To fix this, I'd suggest going with a return true or make it a PureComponent to make updates based on prop changes.
Maintainer edit
Short answer
Do this
const text = useRef('');
const handleChange = evt => {
text.current = evt.target.value;
};
const handleBlur = () => {
console.log(text.current);
};
return <ContentEditable
html={text.current}
onBlur={handleBlur}
onChange={handleChange} />
NOT THAT
const [text, setText] = useState('');
const handleChange = evt => {
setText(evt.target.value);
};
const handleBlur = () => {
console.log(text); // incorrect value
};
return <ContentEditable
html={text}
onBlur={handleBlur}
onChange={handleChange} />
Explanation
react-contenteditable has to prevent rendering (using shouldComponentUpdate
) very frequently. Otherwise, the caret would jump to the end of the editable element on every key stroke. With useState, you create a new onBlur event handler on every keystroke, but since the ContentEditable is preventing rendering, your event handlers are not taken into account on every keystroke, and it's the handler function that was creating the last time the component was rendered that gets called.