How to change the background color of the Chakra UI Toast component?

Viewed 2280

I use Chakra UI and I have several Toast components in my application. They have a blue background color by default since they have status="info".

How can I change the background color of all the toasts with status="info"? And I want to keep all other default styles (width, position etc.), need to change only color.

2 Answers

The Toast component uses Alert under the hood.

Alert maps the status prop to a color scheme. This color scheme is used in the theme definition to define the background color.

By default, status="info" maps to blue and the subtle variant is used.

Hence you would need add an override like this to your theme definition:

import { theme as origTheme, extendTheme } from "@chakra-ui/react"

const theme = extendTheme({
  components: {
    Alert: {
      variants: {
        subtle: (props) => { // only applies to `subtle` variant
          const { colorScheme: c } = props
          if (c !== "blue") {
            // use original definition for all color schemes except "blue"
            return origTheme.components.Alert.variants.subtle(props)
          }
          return {
            container: {
              bg: `${c}.500`, // or literal color, e.g. "#0984ff"
            },
          }
        }
      }
    }
  }
})

Color variables like blue.500 are read from the color definitions.

In the newer versions of Chakra, Toasts are indeed using Alerts under the hood but they have switched to using the solid variant of Alert from subtle. Styling the solid variant of Alert will style your Toast.

Related