Add event listener to ref in React context
P粉765570115
P粉765570115 2024-01-29 00:12:47
0
1
420
The

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!

P粉765570115
P粉765570115

reply all(1)
P粉668146636

blur events do not bubble, but you can use the related focusout event to handle child elements losing focus.

if (element) {
  element.addEventListener('focusout', blurHandler);
} else return;

return () => element.removeEventListener('focusout', blurHandler);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template