For external controlled component
If you are using V3, i would recommend to use react-hook-form-input
https://github.com/react-hook-form/react-hook-form-input
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' },
];
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">Reset Form</button>
<button>submit</button>
</form>
);
}
If you are using V4, i would recommend to use Controller
https://react-hook-form.com/api/#Controller
import React from 'react';
import Select from 'react-select';
import { TextField } from "@material-ui/core";
import { useForm, Controller } from 'react-hook-form';
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' },
];
function App() {
const { handleSubmit, control } = useForm();
return (
<form onSubmit={handleSubmit(data => console.log(data))}>
<Controller
as={<Select options={options} />}
control={control}
rules={{ required: true }}
onChange={([selected]) => {
// React Select return object instead of value for selection
return { value: selected };
}}
name="reactSelect"
/>
<Controller
as={<TextField />}
name="firstName"
control={control}
/>
<button>submit</button>
</form>
);
}
The idea to wrap your controlled component and collecting data within while still isolate re-render inside the external controlled component.
defaultValues
after the creation. codesandbox.io/s/react-hook-form-material-ui-viq6q – SamsetTimeout(() => (setValue("name", 123)), 1000);
– Domino987