I'm trying to use react-hook-form library to validate a form. When I render view using ant design or material UI, it does not work correctly.
<Input name="firstName" ref={register({ required: true })} />
{errors.firstName && 'First name is required'}
Some warning happened: "Missing name at....."
.
React Hook Form (I’m its author) embraces uncontrolled components and native inputs, however it’s hard to avoid working with external controlled components such as React-Select, Ant Design, or Material UI. So I have built a wrapper component to help you integrate easier.
From version 4: Controller
Before version 4: react-hook-form-input
(Code Sandbox example)
Okay, you may wonder what’s the point of doing this, and what are you getting out of React Hook Form with controlled components? First, you still benefit from our in-built validation, or a schema validation at your choice. Second, this will improve your app or form performance by isolating your input state update, which means your form root can be drawn with zero re-renders, or even without a controlled component.
On top this, I have also built a wrapper component to make things a bit easier:
import React from 'react';
import useForm from 'react-hook-form';
import { RHFInput } from 'react-hook-form-input';
import Select from 'react-select';
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' },
];
function App() {
const { handleSubmit, register, setValue, reset } = useForm();
return (
<form onSubmit={handleSubmit(data => console.log(data))}>
<RHFInput
as={<Select options={options} />}
rules={{ required: true }}
name="reactSelect"
register={register}
setValue={setValue}
/>
<button
type="button"
onClick={() => {
reset({
reactSelect: '',
});
}}
>
Reset Form
</button>
<button>submit</button>
</form>
);
}
Hopefully this makes sense and that extra component which I have created helps you, too.