Saturday, May 25, 2024
 Popular · Latest · Hot · Upcoming
rated 0 times [  75] [ 5]  / answers: 1 / hits: 16150  / 4 Years ago, tue, april 28, 2020, 12:00:00

I have been using react hook form library with native elements but would like to switch to custom components using the Controller API.

I am having an issue with my custom input component updating React state but not updating the ref inside the form state. Thus, a required field is always marked as invalid and I cannot submit my form.

Here is a demo of my issue:

It should log out form data upon submission - but submission never happens because form is not valid.

More From » reactjs


I think I have narrowed down your issue. First I removed the rules={{ required: true }} from the controller and tried the form. It told me firstName: undefined. Then I commented out the onChange attribute. After that, the form is working fine. It seems that onChange should be used if you want to provide a custom value extractor. The value needs to be returned from the function. An example of a simple input would be this: onChange={([{target}]) => target.value} reference. Additionally, it is important to note that handleSubmit extracts some internal state with the values, like that you don't need to keep track of those yourself.

This updated component seems to be working:

function App() {
const { control, handleSubmit, errors } = useForm();
// const [data, setData] = useState({ firstName: });

const onSubmit = data => console.log(data);

// const onChangeHandler = e => {
// const { name, value } =;
// const _data = { };
// _data[name] = value;
// setData(_data);
// };

return (
{/* <p>{JSON.stringify(data)}</p> */}
<form onSubmit={handleSubmit(onSubmit)}>
label=First Name
// value={data.firstName}
rules={{ required: true }}
// onChange={([e]) => onChangeHandler(e)}

<input type=submit />

Just a side note, I've never worked with this library so only trust me as far as you can toss me.

[#50991] Tuesday, April 21, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.

Total Points: 490
Total Questions: 94
Total Answers: 94

Location: Lebanon
Member since Sun, Aug 2, 2020
4 Years ago