From 75e5015cc5240e2dd42f51cd8d9ed0421472fa2a Mon Sep 17 00:00:00 2001 From: Dylan Markow Date: Wed, 4 Dec 2019 14:01:41 -0600 Subject: [PATCH] Handle autoFocus after mounting (#3226) --- .../slate-react/src/components/editable.tsx | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/packages/slate-react/src/components/editable.tsx b/packages/slate-react/src/components/editable.tsx index 60caa7745..f2478e60d 100644 --- a/packages/slate-react/src/components/editable.tsx +++ b/packages/slate-react/src/components/editable.tsx @@ -1,4 +1,10 @@ -import React, { useLayoutEffect, useRef, useMemo, useCallback } from 'react' +import React, { + useLayoutEffect, + useEffect, + useRef, + useMemo, + useCallback, +} from 'react' import { Editor, Element, NodeEntry, Node, Range, Text, Mark } from 'slate' import debounce from 'debounce' import scrollIntoView from 'scroll-into-view-if-needed' @@ -96,6 +102,7 @@ export const Editable = ( renderDecoration, renderElement, renderMark, + autoFocus, style = {}, onDOMBeforeInput: propsOnDOMBeforeInput, ...attributes @@ -210,6 +217,14 @@ export const Editable = ( }) }) + // The autoFocus TextareaHTMLAttribute doesn't do anything on a div, so it + // needs to be manually focused. + useEffect(() => { + if (ref.current && autoFocus) { + ref.current.focus() + } + }, [autoFocus]) + // Listen on the native `beforeinput` event to get real "Level 2" events. This // is required because React's `beforeinput` is fake and never really attaches // to the real event sadly. (2019/11/01)