How to change default color of Chakra Theme?

184 Views Asked by At

I'm customizing the colors of my project using Chakra UI, but I came across a situation that I couldn't find in the project's documentation.

Well, I used extendTheme to change the green colors.

const theme = extendTheme({
  colors: {
    green: {
      50: "#ecfdf5",
      100: "#d1fae5",
      200: "#a7f3d0",
      300: "#6ee7b7",
      400: "#34d399",
      500: "#10b981",
      600: "#059669",
      700: "#047857",
      800: "#065f46",
      900: "#064e3b",
    },
  },
});

This in itself is working. When I use it in a component, for example:

<Box bg="green.400" />

The problem arises when I try to use just the name green. It uses the default green from CSS and not one of the 50-900 shades of green that I defined. I don't know how I can define a color to be the default.

2

There are 2 best solutions below

0
On

The key word that helped me find the solution was semanticTokens.

With this configuration, I managed to define a token for the green color.

const theme = extendTheme({
      semanticTokens: {
        colors: {
          green: "green.500",
        },
      },
      colors: {
        green: {
          50: "#ecfdf5",
          100: "#d1fae5",
          200: "#a7f3d0",
          300: "#6ee7b7",
          400: "#34d399",
          500: "#10b981",
          600: "#059669",
          700: "#047857",
          800: "#065f46",
          900: "#064e3b",
        },
      },
    });

More information can be found at:

https://chakra-ui.com/docs/styled-system/semantic-tokens

In the documentation, they use terms like success, danger, error, etc. But color names can also be applied.

0
On

Kind of, but 'green' itself doesn't have much of a semantic meaning. Compared to their example of 'success'.

The better way to approach this at the component level is to use a component theme

https://chakra-ui.com/docs/styled-system/component-style#consuming-style-config

So you create a component, say, Card, and build a theme up for the Card component, giving it a bgColor of green.500 or whatever.

const Card = defineStyleConfig({
  baseStyle: {
    bgColor: 'green.500'
  }
})

then after adding Card to your theme, do -

function Card(props) {
  const styles = useStyleConfig('Card')

  return <Box __css={styles} {...props} />
}

Then everywhere you will just render your <Card>...</Card> component.

For complex components, you can use a multi-style config - https://chakra-ui.com/docs/styled-system/component-style#styling-multipart-components whereby you define each of the 'parts' of your component, and give each part its own theme.