Home  >  Q&A  >  body text

Add event listener to ref in React context

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粉765570115P粉765570115287 days ago402

reply all(1)I'll reply

  • P粉668146636

    P粉6681466362024-01-29 00:40:55

    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);
    

    reply
    0
  • Cancelreply