Last active
April 3, 2018 19:21
-
-
Save aweary/c36e12a710455e8435f3faa7cbb4cf37 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import { createSubscription } from 'create-subscription' | |
// Create the subscription, which will manage adding and removing the | |
// event listener for us when the component mounts and unmounts, respectively. | |
const AddEventListenerSubscription = createSubscription({ | |
getCurrentValue() { | |
// Since there's no "current value" for an event listener, we just | |
// implicitly return `undefined` | |
}, | |
subscribe({ source, event }, callback) { | |
source.addEventListener(event, callback) | |
return () => source.removeEventListener(event, callback) | |
}, | |
}) | |
// A small wrapper around the subscription which defines the API | |
// and manages calling the listener prop when an event is dispatched. | |
const AddEventListener = ({ source, event, listener }) => ( | |
<AddEventListenerSubscription source={{ source, event }}> | |
{event => { | |
// Call the callback when the event exists! Remember, it can be null | |
// since we return null from getCurrentValue | |
if (event) listener(event) | |
// This component just registers a subscription, so render null | |
return null | |
}} | |
</AddEventListenerSubscription> | |
) | |
// An async-safe, declarative API for registered DOM event listeners! | |
const KeyListener = () => ( | |
<AddEventListener | |
source={window} | |
event="keydown" | |
listener={event => console.log(`You pressed ${event.key}`)} | |
/> | |
) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment