ui
ui copied to clipboard
Checkbox onCheckedChange not compatible with Form field.onChange
Using <Checkbox /> with the latest shadcn/ui CLI, as well as <Form /> elements:
<FormField
control={form.control}
name="isFeatured"
render={({ field }) => (
<FormItem className="flex flex-row items-start space-x-3 space-y-0 rounded-md border p-4">
<FormControl>
<Checkbox
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
<div className="space-y-1 leading-none">
<FormLabel>
Featured
</FormLabel>
<FormDescription>
This product will appear on the home page
</FormDescription>
</div>
</FormItem>
)}
/>
Yields the following TS error:
Schema for the checkbox field:
isFeatured: z.boolean().default(false).optional()
Followed instructions from https://ui.shadcn.com/docs/components/checkbox
I believe this is due to the latest update from react-hook-forms. There is an issue on their Github here: https://github.com/react-hook-form/react-hook-form/pull/10342
To make it working you can roll back to [email protected]
@shadcn - components will need to likely be updated to follow the new input types for onChange functions - which brings me nicely to my next question: How do we update shadcn UI components in our projects? 🤔
How do we update shadcn UI components in our projects?
To update your project you can follow the guide in the changelog. To update the components you can run the add
command again followed by the --overwrite
argument.
Downgrading react-hook-form seemed to fix this for me ✅
There needs to be a solution which does not rely on downgrading react-hook-form Had the same issue, to remove ts complaining, i just did
onCheckedChange={field.onChange}
to
onCheckedChange={field.onChange as () => void}
It works but its not a solution.
This is my workaround:
onCheckedChange={() => field.onChange(!field.value)}
I'm wodering why can we use Controller and control as they give better handling of form component like here
const {
register,
handleSubmit,
control,
setValue,
formState: { errors },
} = useForm<JobIForm>({
resolver: zodResolver(schema),
mode: 'onSubmit',
});
<Controller
control={control}
name='isRemote'
render={({ field: { onChange, value } }) => (
<Checkbox onChange={onChange} checked={value} />
)}
/>
{errors.isRemote?.message !== undefined ? (
<p className='text-sm text-destructive'>
{errors.isRemote.message}
</p>
) : (
<p className='text-sm text-muted-foreground'>
Please indicates the compensation or pay range for the job
position
</p>
)}
</div>
onCheckedChange={(value) => {
field.onChange(value);
}}
this worked for me
This issue has been automatically closed because it received no activity for a while. If you think it was closed by accident, please leave a comment. Thank you.