skip to Main Content

I have a problem with shadcn’s <FormLabel>. How do prevent it from showing a color of red (It actually add a text-destructive automatically) when a field has error/required.
I only want the <FormMessage/> to change the color.

<FormField
    control={form.control}
    name="name"
    render={({ field }) => (
        <FormItem>
            <FormLabel>Project Name</FormLabel>
            <FormControl>
                <Input placeholder="Enter project name" {...field} />
            </FormControl>
            <FormMessage />
        </FormItem>
    )}
/>

3

Answers


  1. You need to make some changes in FormLabel component ( in form.jsx file ) that was build by shadcn cli

    New FormLabel:

    const FormLabel = React.forwardRef<
      React.ElementRef<typeof LabelPrimitive.Root>,
      React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
    >(({ className, ...props }, ref) => {
      const { formItemId } = useFormField()
     
      return (
        <Label
          ref={ref}
          className={className}
          htmlFor={formItemId}
          {...props}
        />
      )
    })
    
    Login or Signup to reply.
  2. You could make changes to the FormLabel itself, but this might be problematic when shadcn is updated. You can simply pass !text-current as a class name to override the behaviour:

    <FormLabel className="!text-current">
    

    You could then create a wrapper around the base FormLabel that does this every time and then use that. This way you avoid touching the generated components, which might make life easier when updating shadcn.

    But if you don’t care about touching them you could just edit the original FormLabel to not actually add text-destructive like Pinal’s answer.

    Login or Signup to reply.
  3. To prevent the label color from changing when there’s an error in the Shadcn UI form, you can override the default behavior by customizing the styles. Here’s how you can do it:

    <FormField
        control={form.control}
        name="name"
        render={({ field }) => (
            <FormItem>
                <FormLabel style={{ color: 'inherit' }}>Project Name</FormLabel>
                <FormControl>
                    <Input placeholder="Enter project name" {...field} />
                </FormControl>
                <FormMessage />
            </FormItem>
        )}
    />
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search