Skip to content

Instantly share code, notes, and snippets.

@elsangedy
Last active November 4, 2020 14:49
Show Gist options
  • Save elsangedy/31a0dbdf208fd7ed990dc3d6ec01ad30 to your computer and use it in GitHub Desktop.
Save elsangedy/31a0dbdf208fd7ed990dc3d6ec01ad30 to your computer and use it in GitHub Desktop.
useImask.ts - https://imask.js.org/
const Comp = () => {
const { getInputProps } = useImask({
mask: [
{
mask: '000.000.000-00',
},
{
mask: '00.000.000/0000-00',
}
],
lazy: true,
unmask: true,
})
return <input {...getInputPropsCardNumber()} />
}
const Comp = () => {
const [value, setValue] = useState('')
const { getInputProps } = useImask({
mask: [
{
mask: '000.000.000-00',
},
{
mask: '00.000.000/0000-00',
}
],
lazy: true,
unmask: true,
value,
onAccept: setValue
})
return <input {...getInputPropsCardNumber()} />
}
import { useRef, useEffect } from 'react'
import IMask from 'imask'
function handleRefs(...refs) {
return (node) => {
refs.forEach((ref) => {
if (typeof ref === 'function') {
ref(node)
} else if (ref) {
ref.current = node
}
})
}
}
export function useImask({ value, unmask, onAccept, onComplete, ...options }: any = {}) {
const imaskRef = useRef(null)
const inputRef = useRef(null)
const getMaskValue = () => {
if (unmask) return imaskRef.current.unmaskedValue
return imaskRef.current?.value
}
const setMaskValue = (newValue) => {
newValue = newValue == null ? '' : newValue
if (unmask) imaskRef.current.unmaskedValue = newValue
else imaskRef.current.value = newValue
}
const _onAccept = (...args) => {
if (onAccept) onAccept(getMaskValue(), imaskRef, ...args)
}
const _onComplete = (...args) => {
if (onComplete) onComplete(getMaskValue(), imaskRef, ...args)
}
const initMask = () => {
if (inputRef.current && options.mask) {
imaskRef.current = IMask(inputRef.current, options).on('accept', _onAccept).on('complete', _onComplete)
setMaskValue(value)
}
}
const destroyMask = () => {
if (imaskRef.current) {
imaskRef.current.off('accept', _onAccept)
imaskRef.current.off('complete', _onComplete)
imaskRef.current.destroy()
imaskRef.current = null
}
}
useEffect(() => {
initMask()
return destroyMask
}, [])
useEffect(() => {
if (imaskRef.current && options.mask) {
if (
value !== getMaskValue() ||
(typeof value !== 'string' && imaskRef.current.value === '' && !imaskRef.current.el.isActive)
) {
setMaskValue(value)
}
}
}, [value])
useEffect(() => {
if (options.mask) {
if (imaskRef.current) {
imaskRef.current.updateOptions(options)
} else {
initMask()
}
} else {
destroyMask()
}
}, [options])
const getInputProps = ({ refKey = 'ref', ref, ...props }: any = {}) => {
return {
...props,
[refKey]: handleRefs(ref, inputRef),
}
}
return {
getInputProps,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment