i'm trying to make my custom component work with react-hook-form, with typescript (react-hook-form 7.31.1, react v 18.0.6, ts 4.6.3). Problem is the value of formState is not what i expect.
This is my code:
App.tsx
import { Controller, useForm } from "react-hook-form";
import InputTest from "./components/forms/input/InputTest";
function App() {
const { handleSubmit, formState, control } = useForm({
mode: "onChange",
});
const onChangeHandler = (data: any) => {
console.log(formState.errors);
};
const onSubmit = (data: any) => {
console.log("submitting...", data);
console.log("errors...", formState.errors);
};
return (
<div className="App">
<form onSubmit={handleSubmit(onSubmit)}>
<Controller
control={control}
name="testinput"
rules={{ required: true, minLength: 5 }}
render={({ field: { onChange, onBlur, value, ref } }) => (
<InputTest
label="testing"
id="123"
value={value}
onChange={(e) => {
onChangeHandler(e);
onChange(e);
}}
></InputTest>
)}
/>
<input type="submit" />
</form>
</div>
);
}
export default App;
InputTest.tsx
import React, { ChangeEvent } from "react";
type inputTestProps = {
value: string;
label: string;
id: string;
/** Function executed when input value changes*/
onChange?: (ev: ChangeEvent<HTMLInputElement>) => void;
};
const InputTest: React.FC<inputTestProps> = (props) => {
const onChangeHandler = (ev: ChangeEvent<HTMLInputElement>) => {
if (props.onChange) props.onChange(ev);
};
return (
<>
<label htmlFor={props.id}>{props.label}</label>
<input id={props.id} onChange={onChangeHandler} />
</>
);
};
export default InputTest;
Problem is that every time i log formState.errors in onChangeHandler,almost every time is not what i'm expecting. Sometimes it logs
{}
sometimes it logs
{testinput: {…}}[[Prototype]]: Objectconstructor: ƒ Object()hasOwnProperty: ƒ hasOwnProperty()isPrototypeOf: ƒ isPrototypeOf()propertyIsEnumerable: ƒ propertyIsEnumerable()toLocaleString: ƒ toLocaleString()toString: ƒ toString()valueOf: ƒ valueOf()__defineGetter__: ƒ __defineGetter__()__defineSetter__: ƒ __defineSetter__()__lookupGetter__: ƒ __lookupGetter__()__lookupSetter__: ƒ __lookupSetter__()__proto__: (...)get __proto__: ƒ __proto__()set __proto__: ƒ __proto__()
and sometimes it logs
testinput:
message: ""
ref: {name: 'testinput'}
type: "minLength"
[[Prototype]]: Object
Am i missing something? I'm using incorrectly? (with a simple input i can make it work easily, but not with custom component )