useRefElement
Aboutβ
Helps bridge gap between callback ref and state. Manages the element called with callback ref api using state variable.
Installationβ
npm install --save rooks
Importing the hookβ
import { useRefElement } from "rooks";
Usageβ
// Build a useEventListenerRef hook using useRefElement
function useEventListenerRef(eventName, callback) {
const [ref, element] = useRefElement();
useEffect(() => {
if (!(element && element.addEventListener)) {
return;
}
element.addEventListener(eventName, callback);
return () => {
element.removeEventListener(eventName, callback);
};
}, [element, eventName, callback]);
return ref;
}
Argumentsβ
No arguments.
Returns an array of two itemsβ
Returned items | Type | Description |
---|---|---|
ref | (refElement: RefElementOrNull<T>) => void | The callback ref |
element | RefElementOrNull<T> | The element linked to the ref |
Codesandbox Exampleβ
Basic usageβ
Join Bhargav's discord serverβ
You can click on the floating discord icon at the bottom right of the screen and talk to us in our server.