@piplup/use-event-listener
Version:
React hook designed to simplify the process of adding event listeners to various DOM elements in React applications.
58 lines (35 loc) • 1.8 kB
Markdown
//img.shields.io/bundlephobia/minzip/@piplup/use-event-listener)
> **Important Notice:** `useEventListener` hook has been moved to [@piplup/utils](https://github.com/sadik-malik/piplup/blob/main/packages/utils/README.md), While it may continue to work for existing projects, we recommend migrating to the new package.
`useEventListener` is a custom React hook designed to simplify the process of adding event listeners to various DOM elements in React applications.
You can install `useEventListener` via npm or yarn:
```bash
npm install @piplup/use-event-listener
yarn add @piplup/use-event-listener
pnpm add @piplup/use-event-listener
```
```jsx
'use client';
import * as React from 'react';
import { useEventListener } from '@piplup/use-event-listener';
function App() {
const handleResize = (event) => {
console.log('Window has been resized!', event);
};
useEventListener('resize', handleResize);
return <div>useEventListener Demo</div>;
}
```
- `eventName` (`string`): The name of the event to listen for, such as `'click'`, `'resize'`, etc.
- `handler` (`function`): The event handler function that will be called when the event is triggered.
- `element` (`RefObject`): A React ref object referencing the DOM element to which the event listener will be attached. If not provided, the event listener will be attached to the `window` object.
- `options` (`AddEventListenerOptions | boolean`, optional): Additional options to pass to the `addEventListener` function.
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
![npm bundle size](https: