I want to add an eventListener to a node in my React component. I am selecting the node with a useRef hook. I am useCallback since the useRef is null on it's first render.
const offeringsContainer = useRef(null);
const setOfferingsContainer = useCallback((node) => {
if (node !== null) {
offeringsContainer.current = node;
}
}, []);
My issue is that my useEffect is not reacting to any changes done to the offeringContainer ref. Meaning, offeringContainer.current is null.
useEffect(() => {
checkHeaderState();
offeringsContainer.current.addEventListener("wheel", onOfferingsContainerWheel, { passive: false });
}, [offeringsContainer.current]);
This is my JSX:
return (
<Fragment>
<div className="card-business-products-services-title-text">
Products & Services
</div>
<div
className="card-business-products-services-container"
id="card-business-products-services-container"
onWheel={onOfferingsContainerWheel}
ref={setOfferingsContainer}
>
{renderOfferings()}
</div>
</Fragment>
);
I know I am doing something incorrectly, but my useEffect hook should be listening to any changes from offeringsContainer.current.
You can just past
offeringsContainerto therefof the component.useEffectwill be invoked only when there is first rendering that's why yourofferingsContainer.currentwill not benull.And you forgot to remove listener after the component will be unmounted.
Your code should be like this;
Example: https://codesandbox.io/s/wizardly-banzai-3fhju?file=/src/App.js