Skip to content

Rewrite the entire thing in TypeScript #36

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions .babelrc

This file was deleted.

6 changes: 0 additions & 6 deletions .eslintrc

This file was deleted.

1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ typings/

# Optional npm cache directory
.npm
example/.cache

# Optional eslint cache
.eslintcache
Expand Down
10 changes: 0 additions & 10 deletions .npmignore

This file was deleted.

4 changes: 0 additions & 4 deletions .prettierrc

This file was deleted.

3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"typescript.tsdk": "node_modules/typescript/lib"
}
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
SOFTWARE.
71 changes: 59 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# @use-it/event-listener

A custom React Hook that provides a declarative useEventListener.
A custom React Hook that provides a declarative addEventListener.

[![npm version](https://badge.fury.io/js/%40use-it%2Fevent-listener.svg)](https://badge.fury.io/js/%40use-it%2Fevent-listener) [![All Contributors](https://img.shields.io/badge/all_contributors-3-orange.svg?style=flat-square)](#contributors)
[![npm version](https://badge.fury.io/js/%40use-it%2Fevent-listener.svg)](https://badge.fury.io/js/%40use-it%2Fevent-listener) [![All Contributors](https://img.shields.io/badge/all_contributors-7-orange.svg?style=flat-square)](#contributors)

This hook was inspired by [Dan Abramov](https://github.com/gaearon)'s
blog post
Expand All @@ -13,6 +13,12 @@ in a custom hook.
That lead to a [chain of tweets](https://twitter.com/donavon/status/1093612936621379584)
between Dan and myself.

## New in version 1.0.0

- Version 1.x has been completely rewritten in TypeScript.
- See [Parameters](#parameters) below for an important breaking change to `element`. Spoiler alert: it's now in `options`.
- Now supports sending a ref as the element as well as a DOM element.

## Installation

```bash
Expand All @@ -30,19 +36,32 @@ $ yarn add @use-it/event-listener
Here is a basic setup.

```js
useEventListener(eventName, handler, element, options);
useEventListener(eventName, handler [, options]);
```

### Parameters
### Parameters <a name="parameters"></a>

Here are the parameters that you can use. (\* = optional).

> Note: in version 1.0, `element` is now a key in `options`. This represents a **breaking change** that _could_ effect your code. Be sure to test before updating to 1.x from version 0.x.

| Parameter | Description |
| :---------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `eventName` | The event name (string). Here is a list of [common events](https://developer.mozilla.org/en-US/docs/Web/Events). |
| `handler` | A function that will be called whenever `eventName` fires on `element`. New in version 1.x: this can also be an object implementing the [EventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventListener) interface. |
| `options`\* | An optional `Options` object (see below). |

Here are the parameters that you can use. (\* = optional)
### Options <a name="parameters"></a>

| Parameter | Description |
| :---------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `eventName` | The event name (string). Here is a list of [common events](https://developer.mozilla.org/en-US/docs/Web/Events). |
| `handler` | A function that will be called whenever `eventName` fires on `element`. |
| `element`\* | An optional element to listen on. Defaults to `global` (i.e., `window`). |
| `options`\* | An object `{ capture?: boolean, passive?: boolean, once?: boolean }` to be passed to `addEventListener`. For advanced use cases. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) for details. |
Here is the Options object. All keys are optional.
See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) for details on `capture`, `passive`, and `once`.

| Key | Description |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `element` | An optional element to listen on. Defaults to `global` (i.e. `window`). In version 1.0.0 this can also be a `refElement` (i.e. the output from `useRef` that you pass to a React element or component) |
| `capture` | A Boolean indicating that events of this type will be dispatched to the registered listener before being dispatched to any `EventTarget` beneath it in the DOM tree. |
| `passive` | A Boolean indicating that the handler will never call `preventDefault()`. |
| `once` | A Boolean indicating that the handler should be invoked at most once after being added. If true, the handler would be automatically removed when invoked. |

### Return

Expand Down Expand Up @@ -79,15 +98,43 @@ and the handler function.
```js
const useMouseMove = () => {
const [coords, setCoords] = useState([0, 0]);

useEventListener('mousemove', ({ clientX, clientY }) => {
setCoords([clientX, clientY]);
});
return coords;
};
```

### TypeScript example

In TypeScript you can specify the type of the `Event` to be more specific. Here we set the handler's event type to `MouseEvent`.

```ts
const useMouseMove = () => {
const [coords, setCoords] = React.useState([0, 0]);
useEventListener('mousemove', ({ clientX, clientY }: MouseEvent) => {
setCoords([clientX, clientY]);
});
return coords;
};
```

### useRef exmple

You can optionally pass a reference instead of an actual element. You might use this when a custom component accapts a ref but doesn't expose a way to pass in specific handlers.

```js
const refElement = React.useRef < HTMLDivElement > null;
useEventListener(
'click',
() => {
alert('You clicked me!');
},
{ element: refElement }
);
return <div ref={refElement}>Click Me</div>;
```

## Live demo

You can view/edit the sample code above on CodeSandbox.
Expand Down
8 changes: 0 additions & 8 deletions __tests__/.eslintrc

This file was deleted.

111 changes: 0 additions & 111 deletions __tests__/index.test.js

This file was deleted.

3 changes: 3 additions & 0 deletions example/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
.cache
dist
20 changes: 20 additions & 0 deletions example/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Playground</title>
<style>
body {
background-color: #333;
color: #eee;
}
</style>
</head>

<body>
<div id="root"></div>
<script src="./index.tsx"></script>
</body>
</html>
55 changes: 55 additions & 0 deletions example/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import useEventListener from '../src';

const useMouseMove = () => {
const [coords, setCoords] = React.useState([0, 0]);
useEventListener(
'mousemove',
({ clientX, clientY }: MouseEvent) => {
setCoords([clientX, clientY]);
},
{ passive: true }
);
return coords;
};

const useKeyDown = () => {
const [key, setKey] = React.useState('');
useEventListener('keydown', (ev: KeyboardEvent) => {
setKey(ev.key);
});
return key;
};

const useClickDiv = () => {
const refElement = React.useRef<HTMLDivElement>(null);
useEventListener(
'click',
() => {
alert('You clicked me!');
},
{ element: refElement }
);
return refElement;
};

const App = () => {
const [x, y] = useMouseMove();
const key = useKeyDown();
const refElement = useClickDiv();

return (
<h1>
<div data-testid="div" ref={refElement}>
Click Me
</div>
<div>
The mouse position is ({x}, {y})
</div>
<div>Last key pressed: {key}</div>
</h1>
);
};

ReactDOM.render(<App />, document.getElementById('root'));
Loading