From 3e147ec5b40eaf030f54a11be5156bfcb136f551 Mon Sep 17 00:00:00 2001 From: Matchu Date: Wed, 7 Oct 2020 10:17:52 -0700 Subject: [PATCH] oops, don't auto-focus feedback button on load --- src/app/HomePage.js | 39 ++++++++++++++++++++++++++------------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/src/app/HomePage.js b/src/app/HomePage.js index b135b1f..a11c3b4 100644 --- a/src/app/HomePage.js +++ b/src/app/HomePage.js @@ -252,18 +252,31 @@ function FeedbackFormSection() { const openButtonRef = React.useRef(null); const emailFieldRef = React.useRef(null); + const elementAwaitingFocusRef = React.useRef(null); + const openForm = React.useCallback(() => { + setIsOpen(true); + + // Wait for the re-render to enable the field, then focus it. + elementAwaitingFocusRef.current = emailFieldRef.current; + }, [setIsOpen]); + + const closeForm = React.useCallback(() => { + setIsOpen(false); + + // Wait for the re-render to enable the button, then focus it. + elementAwaitingFocusRef.current = openButtonRef.current; + }, [setIsOpen]); + + // This lil layout effect will focus whatever element is awaiting focus, then + // clear it out. We use this to set up focus() calls, but wait until the next + // layout finishes to actually call them. React.useLayoutEffect(() => { - if (isOpen) { - if (emailFieldRef.current) { - emailFieldRef.current.focus(); - } - } else { - if (openButtonRef.current) { - openButtonRef.current.focus(); - } + if (elementAwaitingFocusRef.current) { + elementAwaitingFocusRef.current.focus(); + elementAwaitingFocusRef.current = null; } - }, [isOpen]); + }); return ( setIsOpen(true))} + onClick={!isOpen ? openForm : null} > } size="xs" variant="ghost" - onClick={() => setIsOpen(false)} + onClick={closeForm} isDisabled={!isOpen} /> @@ -331,7 +344,7 @@ function FeedbackFormSection() { > setIsOpen(true)} + onClick={openForm} openButtonRef={openButtonRef} /> @@ -344,7 +357,7 @@ function FeedbackFormSection() { > setIsOpen(false)} + onClose={closeForm} emailFieldRef={emailFieldRef} />