Same problem. That's what I came up with. https://stackblitz.com/edit/react-ts-b557bc?file=App.tsx
import * as React from 'react';
import './style.css';
import { useForm, useWatch, Controller } from 'react-hook-form';
export default function App() {
const {
register,
handleSubmit,
control,
unregister,
formState: { errors },
} = useForm({
defaultValues: {
isOnline: true,
isRegular: false,
urlAddress: '',
cityAddress: '',
startDate: '',
},
});
const [isOnline, isRegular] = useWatch({
control,
name: ['isOnline', 'isRegular'],
});
const onSubmit = (data) => console.log('data: ', data);
console.log('errors: ', errors);
React.useEffect(() => {
if (isOnline) {
register('urlAddress');
unregister('cityAddress');
} else {
register('cityAddress');
unregister('urlAddress');
}
}, [register, unregister, isOnline]);
React.useEffect(() => {
if (isRegular) {
register('startDate');
} else {
unregister('startDate');
}
}, [register, unregister, isRegular]);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Controller
control={control}
name="isOnline"
render={({ field: { onChange, value } }) => (
<input
type="checkbox"
checked={value}
value={value}
onChange={onChange}
/>
)}
/>
{isOnline ? (
<Controller
control={control}
name="urlAddress"
rules={{ required: { value: true, message: 'urlAddress required' } }}
render={({ field: { onChange, value }, fieldState: { error } }) => (
<div>
<div>urlAddress</div>
<input type="text" value={value} onChange={onChange} />
error: {error?.message}
</div>
)}
/>
) : (
<Controller
control={control}
name="cityAddress"
rules={{ required: { value: true, message: 'cityAddress required' } }}
render={({ field: { onChange, value }, fieldState: { error } }) => (
<div>
<div>cityAddress</div>
<input type="text" value={value} onChange={onChange} />
error: {error?.message}
</div>
)}
/>
)}
<Controller
control={control}
name="isRegular"
render={({ field: { onChange, value } }) => (
<input type="checkbox" value={value} onChange={onChange} />
)}
/>
{isRegular && (
<Controller
control={control}
name="startDate"
rules={{ required: { value: true, message: 'startDate required' } }}
render={({ field: { onChange, value }, fieldState: { error } }) => (
<div>
<div>startDate</div>
<input type="text" value={value} onChange={onChange} />
error: {error?.message}
</div>
)}
/>
)}
<input type="submit" />
</form>
);
}