From 8c5004242ab6fa51b3aa1462f002d185392150c6 Mon Sep 17 00:00:00 2001 From: Dan Abramov Date: Mon, 27 Jan 2020 08:43:10 -0800 Subject: [PATCH] Add editorRef prop to DraftEditor Summary: We're gonna use it to remove some findDOMNode usage. This lets you access the actual contentEditable. In the future, we might be able to remove the `.editor` and `.editorContainer` instance fields, and make them both refs. Reviewed By: claudiopro Differential Revision: D19555598 fbshipit-source-id: a86be5370a9fd173b3bb062ecc50cabdf9823b75 --- src/component/base/DraftEditor.react.js | 15 +++++++++++++-- src/component/base/DraftEditorProps.js | 7 +++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/component/base/DraftEditor.react.js b/src/component/base/DraftEditor.react.js index a518660d5b..1136279587 100644 --- a/src/component/base/DraftEditor.react.js +++ b/src/component/base/DraftEditor.react.js @@ -285,6 +285,16 @@ class DraftEditor extends React.Component { }; } + _handleEditorContainerRef: (HTMLElement | null) => void = ( + node: HTMLElement | null, + ): void => { + this.editorContainer = node; + // Instead of having a direct ref on the child, we'll grab it here. + // This is safe as long as the rendered structure is static (which it is). + // This lets the child support ref={props.editorRef} without merging refs. + this.editor = node !== null ? (node: any).firstChild : null; + }; + _showPlaceholder(): boolean { return ( !!this.props.placeholder && @@ -367,7 +377,8 @@ class DraftEditor extends React.Component { {this._renderPlaceholder()}
(this.editorContainer = ref)}> + ref={this._handleEditorContainerRef}> + {/* Note: _handleEditorContainerRef assumes this div won't move: */}
{ onMouseUp={this._onMouseUp} onPaste={this._onPaste} onSelect={this._onSelect} - ref={ref => (this.editor = ref)} + ref={this.props.editorRef} role={readOnly ? null : ariaRole} spellCheck={allowSpellCheck && this.props.spellCheck} style={contentStyle} diff --git a/src/component/base/DraftEditorProps.js b/src/component/base/DraftEditorProps.js index e1ecb7abd8..bd96b1f344 100644 --- a/src/component/base/DraftEditorProps.js +++ b/src/component/base/DraftEditorProps.js @@ -64,6 +64,13 @@ export type DraftEditorProps = { // Function that returns a cx map corresponding to block-level styles. blockStyleFn: (block: BlockNodeRecord) => string, + // If supplied, a ref which will be passed to the contenteditable. + // Currently, only object refs are supported. + editorRef?: ?( + | {|current: null | HTMLElement|} + | ((HTMLElement | null) => void) + ), + // A function that accepts a synthetic key event and returns // the matching DraftEditorCommand constant, or a custom string, // or null if no command should be invoked.