@vdslruf/use-ref-event-listener
v0.1.4
Published
Simple custom hooks for RefObjects
Downloads
6
Maintainers
Readme
@vdslruf/use-ref-event-listener
Simple custom hooks for RefObjects
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