@vdslruf/use-ref-event-listener
TypeScript icon, indicating that this package has built-in type declarations

0.1.4 • Public • Published

@vdslruf/use-ref-event-listener

Simple custom hooks for RefObjects

License: MIT npm version

This hook was inspired by useEventListener

Installation

npm i @vdslruf/use-ref-event-listener

Usage

const refObject = useRefEventListener(eventName, handler, options);

Parameters

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

Parameter Description
eventName The event name (string). Here is a list of common events.
handler A function that will be called whenever eventName fires on element.
options* An object { capture?: boolean, passive?: boolean, once?: boolean } to be passed to addEventListener. For advanced use cases. See MDN for details.

Return

RefObject

Use Case

Like native change events, it dispatches when the change is finalized.

function App(){
  const [ state, setState ] = useState('');
  
  const ref = useRefEventListener('change', e => setState(e.target.value));
  return (
    <>
      <input ref={ref} />
      <output>{state}</output>
    </>
  )
}

Use various DOM API events that React does not support.

function App(){
  const [ log, setLog ] = useState('');
  const ref = useRefEventListener('beforeinput', e => setLog(e.target.value));
  return (
    <>
      <input ref={ref} />
      <output>previous value: {log}</output> 
    </>
  )
}

TypeScript

function Div(props){
  const ref = useRefEventListener<HTMLDivElement>('click', ~);
  return <div ref={ref} {...props}>{props.children}</div>
}

License

MIT Licensed

Package Sidebar

Install

npm i @vdslruf/use-ref-event-listener

Weekly Downloads

0

Version

0.1.4

License

MIT

Unpacked Size

8.4 kB

Total Files

9

Last publish

Collaborators

  • vdslruf