Reputation: 2705
I want to conditional disable input based on another input value. The common use case is we have a checkbox and we need to disable/enable another input in the same form. How could I achieve it with react-hook-form? I want to disable, not about validation when submit.
Currently, I am using FormControlLabel
(material-ui) with react-hook-form for that. Any help will be appreciated.
Updated! Here is a small demo code for my idea
import { Controller, useForm } from "react-hook-form";
import { FormControlLabel, Checkbox } from "@material-ui/core";
const { control } = useForm({/* some options */});
// Below is render function
<form onSubmit={handleSubmit(onSubmit)}>
<Controller
name="checkbox"
control={control}
render={({ field: { onChange, value }}) => {
return (
<FormControlLabel
control={
<Checkbox
checked={value}
onChange={e => {
onChange(e.target.checked);
}}
/>
}
label="Enable text input?"
labelPlacement="end"
/>
);
}}
/>
<Controller
name="text-input"
control={control}
render={({ field: { onChange, value } }) => {
return (
<TextField
value={value}
onChange={onChange}
disabled={/* WHAT TO DO HERE???? */}
/>
);
}}
/>;
</form>
Upvotes: 14
Views: 30004
Reputation: 1213
you can use watch
:
const {register, watch} = useForm();
return (
<div>
<input type="checkbox" ref={register} name="input-a" />
<input ref={register} name="input-b" disabled={!watch("input-a")} />
</div>
);
Upvotes: 26