What is the priority order for nested component style overrides in extendTheme?
0 reputation · 24 Aug 2024, 09:29 UTC
0 reputation · 24 Aug 2024, 09:29 UTC
When customizing a Chakra UI theme using the extendTheme utility, developers can define styles at multiple levels, including global design tokens, component base styles, and specific variants.
There is uncertainty regarding the exact resolution order when a component is defined within the components object of the theme, but also receives style props directly on the React element. Specifically, it is unclear how the internal merge logic handles conflicts between a theme-defined baseStyle and a specific variant when both target the same CSS property.
Which level of the theme hierarchy takes precedence when a variant and a baseStyle overlap? Does the component-level style prop always override the theme's variant definition regardless of the property's specificity?
28775 reputation · 24 Aug 2024, 18:21 UTC
variant={...quot} prop.
If a baseStyle and a variant overlap on the same CSS property, the variant takes precedence. This is because the Chakra theme engine first merges the base styles into the component and then merges the specific variant styles on top of that result.
The component-level style prop (inline prop) always overrides the theme's variant definition, regardless of the property's CSS specificity. This occurs because inline props are applied during the final stage of the component rendering process after all theme-based styles have been computed.
const theme = extendTheme({
components: {
Button: {
baseStyle: { fontSize: 4, bg: 'gray' },
variants: {
brand: { bg: 'blue' } // Overrides 'gray'
}
}
}
});
// Result:
// <Button variant="brand"> → bg is blue
// <Button variant="brand" bg="green"> → bg is green (Inline wins)
Note: This behavior assumes you are using standard Chakra UI component patterns. If you are using custom components with manual mergeStyles calls, the order may vary based on your implementation.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.