Style Chakra UI FormControl and label at application theme level

2.5k Views Asked by At

Have been using Chakra for a while but I can not get my head around styling all my components, in this case, FormControl at a global level with the theme file.

For example if i want to add margin bottom to my FormControl and FormLabel elements I would add the components object to the theme file like so:

  components: {
    Form: {
      parts: ['control', 'label', 'errorMessage'],
      baseStyle: {
        control: {
          marginBottom: '2rem',
        },
        label: {
          marginBottom: '3rem',
        },
      },
    },
  }, 

But this has no effect on the base style of the rendered FormControl or FormLabel.

Could someone please help me with what I am doing wrong here?

3

There are 3 best solutions below

0
On

Having looked through the source code a bit more there is no parts array to FormControl as it is a Context rather than a component. Therefore, it cannot be styled!

1
On

This worked for me:

import type { ComponentStyleConfig } from '@chakra-ui/theme';
import { extendTheme } from '@chakra-ui/react'


const Form: ComponentStyleConfig = {
  // The styles all button have in common
  parts: ['container'],
  baseStyle: {
    /// The container styles the FormControl
    container: {
      marginY: '20px'
    }
  },
}

const theme = extendTheme({
  components: {
    Form,
  },
})
1
On
export const formStyles = {
  parts: ['container', 'requiredIndicator', 'helperText'],
  baseStyle: {
    container: {
      label: {
        fontSize: '14px',
        fontWeight: 'bold',
      },
    },
  },
};

Import it into your component styles

components: {
  Form: formStyles,
}