Update SelectionState on readOnly Editor component
See original GitHub issueDo you want to request a feature or report a bug? Feature request, I presume.
What is the current behavior?
When the Editor component is set to readOnly
, no events are fired at all (e.g. the onChange
method is ignored). This seems to be by design: “Set whether the editor should be rendered as static DOM, with all editability disabled.” However, not even selection events are triggered.
What is the expected behavior?
My use case: I want to render non-editable text within an Editor component (taking advantage of the Entity rendering), but still get an updated SelectionState on each new selection to display a tooltip near the selected text + save the current selection to a Redux store. I can implement this easily without the readOnly attribute:
But once I set the
readOnly
attribute, I have no way of retrieving the current selection from the Editor model. My current workaround is not to set the attribute but instead discard all editor changes apart from selection state updates.
Would be nice to be able to keep onSelect
on the Editor component while disabling all editing with readOnly
, like requested in #467 .
// in constructor
this.onChange = editorState => {
if (this.state.editorState.getCurrentContent() != editorState.getCurrentContent()) {
this.setState( EditorState.undo(editorState) );
} else {
this.props.dispatch(/* action to save raw ContentState + SelectionState to Redux store */);
this.setState( EditorState.undo(editorState) );
}
}
Which versions of Draft.js, and which browser / OS are affected by this issue? Did this work in previous versions of Draft.js? Working with Draft.js 0.9.1, macOS 10.12 + Google Chrome 53.0.2785.116. Didn’t work previously afaik.
Issue Analytics
- State:
- Created 7 years ago
- Reactions:22
- Comments:8
I was able to solve this with a bit of a hack:
In read only mode:
Basically this causes the Editor to return a custom ‘not-handled-command’ for all input including backspace, pasting etc.
https://draftjs.org/docs/advanced-topics-key-bindings.html
Then Draft js looks for this
not-handled-command
in thehandleKeyCommand
prop. Since we don’t pass a custom handleKeyCommand to handle this custom command, nothing seems to change. However selecting stuff still calls theonChange
handler in draft-js so I am able to getonChange
events to fire even in this ‘readOnly’ modeFor someone who finding this solution, the hack from @terencechow is fully block the most of characters, but sadly the composition input method such as Chinese or Japanese could not work at all, and the
handleBeforeInput
also could not catch any of them.