React context provider sets a ref
that is used by another component to set an obfuscated event listener. The problem is that the blur event doesn't fire the listener.
Code excerpt for context provider.
... export function useEditorContext(): EditorContextProps { return useContext(EditorContext) as EditorContextProps; } export default function EditorProvider({ children }: { children: React.ReactNode }) { const ref = useRef<HTMLDivElement>(null); const historyState = useMemo(createEmptyHistoryState, []); const context = { historyState, ref }; return ( <EditorContext.Provider value={context}> <div ref={ref}> {children} </div> </EditorContext.Provider> ); }
The goal is to attach a listener to the Lexical plugin.
const { historyState, ref } = useEditorContext(); const blurHandler = (event: FocusEvent) => { console.log('Blurred'); }; useEffect(() => { const element = ref.current; if (element) { element.addEventListener('blur', blurHandler, false); } else return; return () => { element.removeEventListener('blur', blurHandler); }; }, [ref.current]); // eslint-disable-line
I've run the code with logging and tried several solutions/answers with useRef
and addEventListener
but none of them worked in the above scenario. Any suggestions are welcome!
blur events do not bubble, but you can use the related focusout event to handle child elements losing focus.