0.1.4 • Published 2 years ago

@vdslruf/use-ref-event-listener v0.1.4

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

@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)

ParameterDescription
eventNameThe event name (string). Here is a list of common events.
handlerA 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