From a3dbaf9e6a38d1e367fcea9aad95f8a3df5e7ba4 Mon Sep 17 00:00:00 2001 From: Gazook89 Date: Fri, 11 Oct 2024 22:34:40 -0500 Subject: [PATCH] refactor anchoredBox to handle focus Refactoring the AnchoredBox component because I wanted to set focus on the trigger button when the expanded box was closed. Wrapping the trigger into it's own component, with forwardRef, allows for passing the `ref` to the actual DOM node. Then the `.focus()` method will work on it. --- client/components/anchoredBox.jsx | 44 +++++++++++++++++++++++-------- 1 file changed, 33 insertions(+), 11 deletions(-) diff --git a/client/components/anchoredBox.jsx b/client/components/anchoredBox.jsx index c7d79d2a1..7978e44d4 100644 --- a/client/components/anchoredBox.jsx +++ b/client/components/anchoredBox.jsx @@ -1,5 +1,5 @@ -require('./anchoredBox.less'); -import React, { useState, useRef, useEffect } from 'react'; +import React, { useState, useRef, useEffect, forwardRef } from 'react'; +import './anchoredBox.less'; const AnchoredBox = ({ anchorPoint = 'center', className, children, ...props })=>{ const [visible, setVisible] = useState(false); @@ -8,10 +8,12 @@ const AnchoredBox = ({ anchorPoint = 'center', className, children, ...props })= useEffect(()=>{ const handleClickOutside = (evt)=>{ - if(boxRef.current && - !boxRef.current.contains(evt.target) && - triggerRef.current && - !triggerRef.current.contains(evt.target)){ + if( + boxRef.current && + !boxRef.current.contains(evt.target) && + triggerRef.current && + !triggerRef.current.contains(evt.target) + ) { setVisible(false); } }; @@ -33,18 +35,32 @@ const AnchoredBox = ({ anchorPoint = 'center', className, children, ...props })= iframe.contentWindow.document.removeEventListener('click', handleClickOutside); } }; - }, []); // Empty dependency array to run effect on mount only + }, []); const handleClick = ()=>{ setVisible(!visible); + triggerRef.current?.focus(); + }; + + const handleKeyDown = (evt)=>{ + if(evt.key === 'Escape') { + setVisible(false); + triggerRef.current?.focus(); + } }; return ( <> - -
+ +
handleKeyDown(evt)} + >

{props.title}

{children}
@@ -52,4 +68,10 @@ const AnchoredBox = ({ anchorPoint = 'center', className, children, ...props })= ); }; +const TriggerButton = forwardRef((props, ref)=>( + +)); + export default AnchoredBox;