Skip to content

Instantly share code, notes, and snippets.

@muhrusdi
Created August 1, 2022 13:46
Show Gist options
  • Save muhrusdi/1ac9f0f666f3262d570f7d7f3a4cb701 to your computer and use it in GitHub Desktop.
Save muhrusdi/1ac9f0f666f3262d570f7d7f3a4cb701 to your computer and use it in GitHub Desktop.
import { Controller, get, Message, useFormContext } from "react-hook-form"
import { FormElement, Input as NextInput, InputProps } from "@nextui-org/react"
import { helperText } from "@/utils/constants"
import { PatternType } from "@/types"
import { useIMask } from "react-imask"
import React, { MutableRefObject, useState } from "react"
type Props = {
pattern?: PatternType
message?: string
rule?: object
mask: string
} & Partial<InputProps>
export const InputMask: React.FC<Props> = ({
required,
pattern,
message,
mask,
maxLength,
minLength,
name,
disabled,
...props
}) => {
const { control, formState } = useFormContext()
const error = get(formState.errors, name ?? "")
return (
<Controller
name={name ?? ""}
control={control}
rules={{ required: message ?? required, pattern, maxLength, minLength }}
render={({ field }) => {
const { value, onChange, ref, ...rest } = field
const {
maskRef,
setValue,
unmaskedValue,
setUnmaskedValue,
typedValue,
setTypedValue,
} = useIMask({
ref: field.ref,
mask,
})
const handleChange = (e: React.ChangeEvent<FormElement>) => {
onChange(e)
setValue(e.target.value)
}
return (
<NextInput
{...props}
{...rest}
onChange={handleChange}
aria-label={name}
disabled={disabled}
status={error?.type ? "error" : "default"}
css={{
".nextui-input-helper-text-container": {
position: "relative",
top: 0,
},
}}
helperText={error?.type ? error?.message || helperText : ""}
/>
)
}}
/>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment