Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@aweary
Last active April 3, 2018 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aweary/c36e12a710455e8435f3faa7cbb4cf37 to your computer and use it in GitHub Desktop.
Save aweary/c36e12a710455e8435f3faa7cbb4cf37 to your computer and use it in GitHub Desktop.
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