Search code examples
reactjscheckboxchakra-ui

ChakraUI: How to set the checkbox color in a checked state


I'm using a ChakraUI Checkbox as follows:

export function CheckItem({ color, checked, label, onChange }: CheckItemProps) {
  return (
    <Checkbox
      iconColor="white"
      borderColor={color}
      isChecked={checked}
      onChange={onChange}
      size="lg"
    >
      <Text fontSize="12px">{label}</Text>
    </Checkbox>
  );
}

How do I set the box color of my checkbox when checked?

  • Using bg sets the background of the entire container including the text.

  • Using color sets the color of the text.

  • Using colorScheme doesn't work because I'm using hex values, not colors from my theme.

  • borderColor works as I'd expect in the unchecked state until I check the box, then it's back to the default blue fill.

I've tried all other prop names with the word color in it and none of them work.

I would expect something in the end to look like this:

export function CheckItem({ color, checked, label, onChange }: CheckItemProps) {
  return (
    <Checkbox
      _checked={{
        // I don't know what prop to put here...
      }}
      iconColor="white"
      borderColor={color}
      isChecked={checked}
      onChange={onChange}
      size="lg"
    >
      <Text fontSize="12px">{label}</Text>
    </Checkbox>
  );
}

Solution

  • You can achieve this by using a css selector in _checked to set the needed styles for the control. The reason _checked={{ background: "red" }} doesn't work is because those styles are applied to the container part when the checkbox is checked. Hence the css selector is needed.

    export function CheckItem({ color, checked, label, onChange }: CheckItemProps) {
      return (
        <Checkbox
         _checked={{
            "& .chakra-checkbox__control": { background: "red" }
          }}     
          iconColor="white"
          borderColor={color}
          isChecked={checked}
          onChange={onChange}
          size="lg"
        >
          <Text fontSize="12px">{label}</Text>
        </Checkbox>
      );
    }
    

    You’ll still need to update the border color and pseudo states (hover, focus, etc.) styles but you should be able to do that inside there as well.