Created
August 1, 2022 13:46
-
-
Save muhrusdi/1ac9f0f666f3262d570f7d7f3a4cb701 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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