Skip to content

Commit

Permalink
Add editorRef prop to DraftEditor
Browse files Browse the repository at this point in the history
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
  • Loading branch information
gaearon authored and facebook-github-bot committed Jan 27, 2020
1 parent 0dd3978 commit 8c50042
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
15 changes: 13 additions & 2 deletions src/component/base/DraftEditor.react.js
Expand Up @@ -285,6 +285,16 @@ class DraftEditor extends React.Component<DraftEditorProps, State> {
};
}

_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 &&
Expand Down Expand Up @@ -367,7 +377,8 @@ class DraftEditor extends React.Component<DraftEditorProps, State> {
{this._renderPlaceholder()}
<div
className={cx('DraftEditor/editorContainer')}
ref={ref => (this.editorContainer = ref)}>
ref={this._handleEditorContainerRef}>
{/* Note: _handleEditorContainerRef assumes this div won't move: */}
<div
aria-activedescendant={
readOnly ? null : this.props.ariaActiveDescendantID
Expand Down Expand Up @@ -415,7 +426,7 @@ class DraftEditor extends React.Component<DraftEditorProps, State> {
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}
Expand Down
7 changes: 7 additions & 0 deletions src/component/base/DraftEditorProps.js
Expand Up @@ -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.
Expand Down

0 comments on commit 8c50042

Please sign in to comment.