Skip to content

flowsn4ke/react-events-utils

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

27 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

react-events-utils

A tiny library providing event utils for react. Makes it easy to pass messages / data without any prop chain in complicated situations by using event listeners using useDocumentListener and triggering using the trigger function them on the document through custom events.

You can also use other utility functions to listen to regular events, just passing the target to useEvent or useEventOnce.

Event listeners will be automatically cleaned up for you when components unmount.

Using regular events

useEvent

Listen for a specific event on a given target.

import { useEvent } from "react-events-utils"

function SomeComponent () {
  const target = useRef(null)
  
  useEvent(target, 'click', e => {
    console.log(e)
    doSomething()
  })

  return <div ref={target}>I am the target.</div>
}

Alternatively, you can pass document, window, or any valid DOM node.

useEventOnce

Same as above, except it will only listen to the event one time.

Passing data around

trigger

import { trigger } from "react-events-utils"

const data = { foo: "bar" }

trigger("event-name-here", data)

useDocumentListener

Listen for an event and receive data if needed.

import { useDocumentListener } from "react-events-utils"

useDocumentListener("event-name-here", (event) => {
  const data = event.detail // if you triggered an event with data
  doSomethingWithTheData()
})

useDocumentListenerOnce

Same as above, except it will only listen to the event one time.

About

Utilities and hooks for using events in react

Resources

Stars

Watchers

Forks

Packages

No packages published