The React context provider sets a ref
that is used by another component to set a blur event listener. The problem is that a blur event does not trigger the listener.
Code extract for the 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 the listener in a 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 have run the code with logging and tried several solutions/answers for useRef
and addEventListener
but none worked in the above scenario. Any suggestions are welcome!