I am trying to prevent the form submission on the Input component showPassword state update. It appears that, for some reason, this happens all the time:
Input component:
const renderIconFromType = (
type: HTMLInputTypeAttribute,
iconProps?: IconProps
) => {
const defaultHeight = 20
const defaultWidth = 20
switch (type) {
case 'email':
return (
<Mail
height={defaultHeight}
width={defaultWidth}
{...iconProps}
/>
)
case 'password':
return (
<Lock
height={defaultHeight}
width={defaultWidth}
{...iconProps}
/>
)
default:
return null
}
}
export const Input = ({
register,
placeholder,
name,
errors,
type,
defaultValue,
validation,
isTheme,
disabled,
...rest
}: Props) => {
const [showPassword, setShowPassword] = useState<boolean>(false)
return (
<div className="my-3">
<div className="flex flex-col relative">
<div
className={classNames(
'absolute top-1/2 left-3 -translate-y-1/2 text-global-disabled',
{
'text-global-warning': errors[name],
}
)}
>
{renderIconFromType(type)}
</div>
<input
id={name}
type={showPassword ? 'text' : type}
placeholder={placeholder}
defaultValue={defaultValue}
disabled={disabled}
autoComplete="off"
{...register(name, validation)}
{...rest}
/>
{type === 'password' && (
<button
onClick={() => setShowPassword(!showPassword)}
className="absolute top-1/2 right-3 -translate-y-1/2 text-global-disabled"
>
{showPassword ? (
<Eye height={20} width={20} />
) : (
<EyeOff height={20} width={20} />
)}
</button>
)}
</div>
{errors[name] && (
<p className="text-sm text-global-warning mt-2">
{errors[name]?.message}
</p>
)}
</div>
)
}
export default Input
Form component:
const { error, loading, authWithEmailAndPassword } = useAuthUserContext()
const onSubmit: SubmitHandler<FormProps> = async (data) => {
if (!isValid) {
return
}
const { email, password } = data
await authWithEmailAndPassword(email, password)
}
<form onSubmit={handleSubmit(onSubmit)}>
<Input
name="email"
type="email"
placeholder="Email"
errors={errors}
register={register}
validation={{
required: {
value: true,
message: 'Email is required!',
},
maxLength: {
value: 30,
message: 'Maximum email length is 30!',
},
minLength: {
value: 8,
message: 'Minimum email length is 8!',
},
}}
/>
</form>
I have performed the following actions that keep displaying error messages on clicking the showPassword button, which I would like to prevent:
- Used
useMemoanduseCallbackhooks - Used the
e.preventDefault()within the form submission function (onSubmit)

