useEventListener

Manages event bindings of an element programmatically.


import { useEventListener } from 'primereact/hooks';
         

Events are attached to the document itself by default.


const [bindKeyDown, unbindKeyDown] = useEventListener({
    type: 'keydown',
    listener: (e) => {
        onKeyDown(e);
    }
});

const [bindKeyUp, unbindKeyUp] = useEventListener({
    type: 'keyup',
    listener: (e) => {
        setPressed(false);
    }
});
         

The element to bind and unbind the events is defined with the target option.

Hover Me

const [hover, setHover] = useState(false);
const elementRef = useRef(null);

const [bindMouseEnterListener, unbindMouseEnterListener] = useEventListener({
    target: elementRef,
    type: 'mouseenter',
    listener: () => {
        setHover(true);
    }
});

const [bindMouseLeaveListener, unbindMouseLeaveListener] = useEventListener({
    target: elementRef,
    type: 'mouseleave',
    listener: () => {
        setHover(false);
    }
});