|
| 1 | +# useEventListener |
| 2 | +Hook to simplify add and remove EventListener use. It's persist during rerendering and automatically remove eventlistener on unMount component lifecycle. |
| 3 | + |
| 4 | +## Usage |
| 5 | + |
| 6 | +```tsx |
| 7 | +const UseEventListener = () => { |
| 8 | + const buttonRef = useRef<HTMLButtonElement>(null); |
| 9 | + const remove = useEventListener({ type: "click", listener: (e: Event) => console.log(e) }); |
| 10 | + useEventListener({ |
| 11 | + type: "click", listener: (e: Event) => { |
| 12 | + console.log(e); |
| 13 | + e.stopPropagation(); |
| 14 | + }, element: buttonRef, listenerOpts: {capture: true} }); |
| 15 | + |
| 16 | + return (<> |
| 17 | + <button onClick={() => remove()}>Remove</button> |
| 18 | + <button ref={buttonRef} style={{marginLeft: 10}}>click to log</button> |
| 19 | + </>); |
| 20 | +} |
| 21 | + |
| 22 | +UseEventListener.displayName = "UseEventListener"; |
| 23 | + |
| 24 | +export { UseEventListener }; |
| 25 | +``` |
| 26 | + |
| 27 | +> The component has: |
| 28 | +> - A _buttonRef_ ref variable linked to an button node element. |
| 29 | +> - A _useEventListener_ invocation with these options: _type_="click", _listener_=(e:Event)=>console.log(e). So the eventListener is attached to window and the invocation result is used to initialize a variable remove that remove the eventListener. |
| 30 | +> - A _useEventListener_ invocation like that above but attached at button node by _buttonRef_ with _listenerOpts_ capture=_true_ and that stops event propagation. |
| 31 | +> - A button that, if clicked, invokes the removeEventListener |
| 32 | +> At every click on Demo area the eventListener attached on object window logs in console the event, while the eventListener attached on button logs when button is clicked. When button remove is clicked it removes the eventListener on window object. The button eventListener is removed during component unmount. |
| 33 | +
|
| 34 | + |
| 35 | +## API |
| 36 | + |
| 37 | +```tsx |
| 38 | +useEventListener ({ type, listener, element = window, listenerOpts }: { type: string, listener: (evt: Event | CustomEvent) => void, element?: RefObject<HTMLElement> | Window, listenerOpts?: boolean | AddEventListenerOptions}) |
| 39 | +``` |
| 40 | + |
| 41 | +> ### Params |
| 42 | +> |
| 43 | +> - __options__: _Object_ |
| 44 | +> - __options.type__: _string_ |
| 45 | +event type |
| 46 | +> - __options.listener__: _(evt: Event | CustomEvent) => void_ |
| 47 | +listener to be executed on specified event |
| 48 | +> - __options.element=window?__: _RefObject<HTMLElement> | Window_ |
| 49 | +element on which attaching eventListener |
| 50 | +> - __options.listenerOpts?__: _boolean | AddEventListenerOptions_ |
| 51 | +options for listener |
| 52 | +> |
| 53 | +
|
| 54 | +> ### Returns |
| 55 | +> |
| 56 | +> __remove__: used to manually remove the eventListener |
| 57 | +> - _()=>void_ |
| 58 | +> |
0 commit comments