universal-hooks
v0.4.1
Published
*Read this in other languages: [Русский](README.ru.md)*
Downloads
2
Readme
Universal hooks
Read this in other languages: Русский
Universal hooks - is a small React-hooks library, that usually need in project.
Hooks are written with TypeScript
. At the moment there are these hooks:
- [x]
use-toggle
- [x]
use-outside-event
- [x]
use-keyboard-event
- [ ] use-screen-type
- [ ] use-media-query
- [ ] more...
Usage
Installation
npm i universal-hooks
use-toggle
It's a simple hook to control Boolean
value, it returns methods to set values,
toggle value method and value. use-toggle
hook can optionally take initial value
import { useToggle } from 'universal-hooks';
const { value, toggle, handleOn, handleOff, setValue } = useToggle(false)
use-outside-event
Hook that helps to subscribe on events outside of element. It takes ref
on element, callback
and optionally event type (like click
, dblclick
and other from GlobalEventHandlersEventMap
)
import { useRef } from 'react';
import { useOutsideEvent } from 'universal-hooks';
const callback = () => console.log('It works!')
const Component = () => {
const ref = useRef(null)
useOutsideEvent({ ref, callback, eventType: 'click' })
return <div>
<div ref={ref}>First div</div>
<div>Second div</div>
</div>
}
use-keyboard-event
Hook that helps to subscribe on keyboard events. It takes key
- string with keyboard key, callback
,
optionally event type (like keyup
, keydown
and keypressed
), and optionally isCtrlOrCmdPressed
-
boolean for keyboard shortcuts with ctrl
or cmd
key
import { useRef } from 'react';
import { useKeyboardEvent } from 'universal-hooks';
const callback = () => console.log('It works!')
const Component = () => {
const ref = useRef(null)
// ctrl+j shortcut
useKeyboardEvent({
callback,
key: 'j',
eventType: 'keyup',
isCtrlOrCmdPressed: true,
})
// subscribe on Escape key press
useKeyboardEvent({
callback,
key: 'Escape',
eventType: 'keypress',
})
return <div>
<div ref={ref}>First div</div>
<div>Second div</div>
</div>
}