.changelog/v1.mdx
Checkbox
framer-motionEditable
isDisabled: true is passed.Hooks
useBoolean hook to ensure setter object reference stays
the sameMenu
type=submitframer-motionTheme
Transition
Form Control
Introduced optionalIndicator for FormLabel
Similar to the RequiredIndicator the OptionalIndicator signalizes when a
field is optional.
Layout
Add support for vertical and horizontal spacing options in the Wrap component.
<Wrap spacingX="2" spacingY="4">
<Box />
<Box />
<Box />
<Box />
</Wrap>
Falls back to the
spacingprop for by default
Editable
setPrevValue onFocus to avoid an outdated prev value when the field
is controlledHooks
Layout
noreferrer attribute from link componentRadio
Styled System
number type for text underline offset of text decoration propsTabs
Toast
Checkbox, Radio
inputProps to underlying input elementModal
onCloseComplete prop to Modal which is called when all DOM nodes of the
Modal are removed.Styled System
_dark and _light pseudo selectors to allow semantic tokens to
change with the data-theme attributes.System
[data-theme] to the CSS variables root selector. This allows the
semantic tokens to change according to data-theme="dark" and
data-theme="light" DOM element attributes.Tooltip
Hooks
isLazy did not work as expected. This was
achieved by updating the hook useAnimationState.Layout
Media Query
useBreakpoint with defaultValue specified in SSRuseBreakpointValue in CSR did not match
SSR.Menu
null as value of icon prop in MenuOptionItem
still rendered the icon.Popover
isLazy did not work as expected. This was
achieved by updating the hook useAnimationState.Anatomy
textarea part to editableAnatomyCLI
Color Mode
ColorModeScript.Editable
Added the component EditableTextarea to Editable. Use the textarea element
to handle multi line text input in an editable context.
<Editable defaultValue="Change me" onChange={console.log}>
<EditablePreview />
<EditableTextarea />
</Editable>
Theme
textarea element in EditableAll Packages
Checkbox
FormControl support for useCheckboxIcon
CreateIconOptionsMedia Query
useBreakpoint did not update after the first
page load.useBreakpointValue hook did not work as expected
with custom breakpointsModal
useAriaHidden hook dependency to make it work as expectedSwitch
Tag
Utils
queryString() created invalid media queries when min
and max were set.Accordion, Anatomy, Theme
root to the Accordion component. It is applied to
the topmost DOM element.Styled System
Modify theme types to make it possible to customize token types via TypeScript module augmentation and declaration merging in addition to allowing customization via the Chakra CLI.
This makes it possible to do the following:
To customize themes using the new mechanism, augment the CustomThemeTypings
type in a definitions file such as types/chakra.d.ts:
⚠️ NOTE: your
CustomThemeTypingsmust implement/extendBaseThemeTypings, otherwise the types will fall back to the default Chakra types (or custom output from @chakra-ui/cli)
import { BaseThemeTypings } from "@chakra-ui/styled-system";
type DefaultSizes = 'small' | 'medium' | 'large';
declare module "@chakra-ui/styled-system" {
export interface CustomThemeTypings extends BaseThemeTypings {
// Example custom `borders` tokens
borders: 'none' | 'thin' | 'thick';
// ...
// Other custom tokens
// ...
components: {
Button: {
// Example custom component sizes and variants
sizes: DefaultSizes;
variants: 'solid' | 'outline' | 'wacky' | 'chill';
};
// ...
}
}
System
Allow all JSX.IntrinsicElements for the chakra factory. This allows to use
every DOM element
with the shorthand version:
<chakra.header>Header</chakra.header>
<chakra.main>Main</chakra.main>
<chakra.footer>Many more</chakra.footer>
All Packages
CLI
1. This
resolves an issue where failures exited with a success status code.Form Control
useMemo from FormControlInput
InputLeftElement and InputRightElement.System
Toast
useToast function returned a new object on every
render.Tooltip
bg, background, bgColor and backgroundColor now.Utils
Input
htmlSize to Input to allow the usage of the native input
attribute size.All Components
Checkbox
CLI
Media Query
Color Mode
Button
iconSpacing for the <ButtonSpinner /> was
hardcoded.Checkbox
CheckboxState type to the useCheckbox hook to improve usability
and documentationHooks
Media Query
Menu, Popover
Number Input
Slider
index in use-range-sliderStyled System
_placeholderShown selectorSystem
ThemingProps to allow string values for the props variant and
size even on components which are not in the default theme.Theme Tools
StyleConfig and MultiStyleConfig
types to reflect the possible usage of style functions instead of style
objects.Color Mode, Styled System, Theme
Introducing semantic tokens
Semantic tokens provide the ability to create css variables which can change with a CSS condition.
import { ChakraProvider, extendTheme } from "@chakra-ui/react"
const customTheme = extendTheme({
colors: {
900: "#171923",
},
})
const App = () => (
<ChakraProvider theme={customTheme}>
<Text color="gray.900">will always be gray.900</Text>
</ChakraProvider>
)
import { ChakraProvider, extendTheme } from "@chakra-ui/react"
const customTheme = extendTheme({
colors: {
50: "#F7FAFC",
900: "#171923",
},
semanticTokens: {
colors: {
text: {
default: "gray.900",
_dark: "gray.50",
},
},
},
})
const App = () => (
<ChakraProvider theme={customTheme}>
<Text color="text">
will be gray.900 in light mode and gray.50 in dark mode
</Text>
</ChakraProvider>
)
import { extendTheme } from "@chakra-ui/react"
const theme = extendTheme({
colors: {
red: {
100: "#ff0010",
400: "#ff0040",
500: "#ff0050",
700: "#ff0070",
800: "#ff0080",
},
},
semanticTokens: {
colors: {
error: "red.500", // create a token alias
success: "red.100",
primary: {
// set variable conditionally with pseudo selectors like `_dark` and `_light`
// use `default` to define fallback value
default: "red.500",
_dark: "red.400",
},
secondary: {
default: "red.800",
_dark: "red.700",
},
},
},
})
Hooks
useAnimationState hook to help track motion component animations. Used
in popopover and menu lazy modesNumber Input
format, parse and character validation callbacks.Styled System
System
<CSSVars root=":host, :root" /> to allow rehoisting CSS
varsTheme
Add entrypoints to the different parts of the theme (colors, fonts, components, spacing, etc.)
// Now you can use only colors from the theme
import colors from "@chakra-ui/theme/foundations/colors"
Here's a table of the theme parts and entrypoints
| Part | Entrypoint |
|---|---|
| components | "@chakra-ui/theme/components" |
| foundations | "@chakra-ui/theme/foundations" |
| colors | "@chakra-ui/theme/foundations/colors" |
| sizes | "@chakra-ui/theme/foundations/sizes" |
| spacing | "@chakra-ui/theme/foundations/spacing" |
| typography | "@chakra-ui/theme/foundations/typography" |
| radius | "@chakra-ui/theme/foundations/radius" |
| shadows | "@chakra-ui/theme/foundations/shadows" |
| transition | "@chakra-ui/theme/foundations/transition" |
| zIndex | "@chakra-ui/theme/foundations/z-index" |
| blur | "@chakra-ui/theme/foundations/blur" |
| borders | "@chakra-ui/theme/foundations/borders" |
Utils
Add helper function flatten
import { flatten } from "@chakra-ui/utils"
flatten({ space: [0, 1, 2, 4, 8, 16, 32] })
/** =>
{
"space.0": 0,
"space.1": 1,
"space.2": 2,
"space.3": 4,
"space.4": 8,
"space.5": 16,
"space.6": 32,
}
*/
CLI
--out path to
node_modules/@chakra-ui/styled-system/dist/declarations/src/theming.types.d.tsTheme
Avatar
srcSet to the <Avatar /> and <AvatarImage /> components
to allow responsive image sources.
Read more on MDNLayout
support for area prop on GridItem
Deprecated area prop on Grid and added support for area prop to be used
with GridItem instead. This allows for usage of GridItem's that have named
template areas to be used in conjunction with a Grid that has a defined
template area.
<Grid templateAreas='"one two three"'>
<GridItem area="one">one</Grid>
<GridItem area="two">two</Grid>
<GridItem area="three">three</Grid>
</Grid>
Modal
DrawerProps type to include ThemingProps for the Drawer componentSystem
Storybook Addon
Checkbox
isDisabled is set to true and
checkbox has focus.CLI
prettier is not installedEditable
Editable component has its startsWithEditView set to true, then
focus should be set to the EditableInput element when the component is
mounted.Hooks
useState alternativeuseId generated inconsistent id values between client
and server (SSR).Media Query
useBreakpointValue returns the correct value on first tick, if matchMedia
is availableMenu
disabled and aria-disabled props from MenuItemProps typesRadio
aria-describedby to the radio props to improve accessibilitySlider
Slider and SliderFilledTrack to be added to
the class listTest Utils
@testing-library/react-hooks to test SSR. This was used to debug and
fix issues with the useId hook.Theme
FormErrorMessage and FormHelperTextModalFooter was out of the viewport for
size="full".Tooltip
CLI
blur, borderStyles and borderWidths.CLI, System
Use the feature flag --strict-component-types for @chakra-ui/cli tokens to
generate strict component type for the theming props variant and size.
chakra-cli tokens --strict-component-types
// before
<Button variant="abc" />
// valid type but variant is not available in the theme
// after
<Button variant="abc" /> // invalid
// Type '"abc"' is not assignable to type '"link" | "outline" | "ghost" | "solid" | "unstyled" | undefined'.
Storybook Addon
The official Storybook Addon for Chakra UI.
yarn add -D @chakra-ui/storybook-addon
npm i -D @chakra-ui/storybook-addon
Add the addon to your configuration in .storybook/main.js:
module.exports = {
addons: ["@chakra-ui/storybook-addon"],
}
Styled System
peer pseudo style props
You can now style an element based on the state of its general sibling (marked
with .peer or data-peer) attribute.
<>
<input type="checkbox" data-peer />
<Box bg="white" _peerFocus={{ bg: "green.400" }} />
</>
The peer properties you can apply are _peerHover, _peerFocus,
_peerFocusVisible, _peerActive, _peerInvalid,
_peerChecked,_peerFocusWithin, _peerPlaceholderShown, _peerDisabled
Added _placeholderShown pseudo props for styling elements when sibling
inputs have placeholder shown.
Added _ltr pseudo props for styling elements in LTR writing mode. This is
useful for products with RTL first approach.
Added _mediaReduceMotion pseudo props to apply reduce motion styles to
elements. This is useful when you need to remove CSS animations/transitions.
Adds style props for CSS scroll behavior properties: scrollPadding,
scrollMargin, scrollSnapAlign, etc...
Here's a full list of properties:
Scroll Behavior: scrollBehavior, scrollSnapAlign, scrollSnapStop,
scrollSnapType
Scroll Margin: scrollMargin, scrollMarginTop, scrollMarginBottom,
scrollMarginLeft, scrollMarginRight, scrollMarginX, scrollMarginY
Scroll Padding: scrollPadding, scrollPaddingTop,
scrollPaddingBottom, scrollPaddingLeft, scrollPaddingRight,
scrollPaddingX, scrollPaddingY
Layout
ListItem without wrapping in List.Input
InputGroup passes undefined size and variant props
which overrides the ones defined by default in a custom Input component.Layout
gap, rowGap and
columnGap we added to styled system.Media Query
useMediaQuery hook.Menu
enabled TS type was exposed to popover and menu from
UsePopperProps. This was resolved by omitting enabled from the typePopover
enabled TS type was exposed to popover and menu from
UsePopperProps. This was resolved by omitting enabled from the typePopover will be display:none when inner element focused.React
@chakra-ui/react to
https://storybook.chakra-ui.comStyled System
bgGradient parser doesn't work when a position is specifiedinset property doesn't work.System
Theme
Toast
Tooltip
onKeyDown callback from de/registering on every call of useTooltipTransition
ref of Slider returns null due to prop overrideLayout, Styled System
Add support for style props gap, columnGap and rowGap. Those CSS
properties are valid in a grid or flex context
For further information see MDN Docs
Popover
Add PopoverAnchor component which allows you to set the Popover reference
point without acting as a trigger.
<Popover>
<PopoverTrigger>
<button>Trigger</button>
</PopoverTrigger>
<PopoverAnchor>
<Box width="40px" height="40px" />
</PopoverAnchor>
<PopoverContent>Hello World</PopoverContent>
</Popover>
Toast
The toast function now exposes a containerStyle property you can use to
override the default styles for the toast container.
function Example() {
// Via instantiation
const toast = useToast({
position: "top",
title: "Container style is customizable",
containerStyle: {
maxWidth: "100%",
},
})
// Or via trigger
return (
<Button
onClick={() => {
toast({
containerStyle: {
maxWidth: "100%",
},
})
}}
>
Click me to show toast with custom container style.
</Button>
)
}
Icon (breaking)
Auto assign key when passing array of paths to createIcon
const HeartIcon = createIcon({
displayName: "HeartIcon",
path: [<path stroke="none" d="..." fill="none" />, <path d="..." />],
})
Color Mode
Fixed flaky color-mode test
Fixed issue where DarkMode and LightMode elements rerenders their children
even if the child is memoized.
<LightMode> and <DarkMode> components are now memoized to prevent
unnecessary rendering of their child components.
Radio
pointer to the radio containerSlider
Props Docs
dist folder and doesn't work when
installed from npm.All Components
Media Query
useColorModePreference returned incorrect values due to
array destructuring.Color Mode
Fixed color mode behavior priority in the following order:
if useSystemColorMode is true system-color will be used as default -
initial colormode is the fallback if system color mode isn't resolved
if --chakra-ui-color-mode is defined through e.g. ColorModeScript this
will be used
if colorModeManager = localStorage and a value is defined for
chakra-ui-color-mode this will be used
if initialColorMode = system system-color will be used as default -
initial colormode is the fallback if system color mode isn't resolved
if initialColorMode = 'light'|'dark' the corresponding value will be
used
Modal
[email protected] includes a dependency update of focus-lock from
0.8.1 -> 0.9.1. The change in focus-lock includes a fix for performance
in JSDOM:
https://github.com/theKashey/focus-lock/pull/24
JSDOM is used when testing react components in jest and other unit testing
frameworks. In particular, when used with @testing-library/react for
simulating real user input.
Locally tested on an Apple M1 Air using a moderately complex <Modal>
component (which contained inputs, react-hook-form usage, etc). Before this
change: 20,149ms After this change: 2,347ms
Approx. 10x performance increase.
Select, Theme
Select component.Slider
RangeSlider where an index out of bounds error would occur
incase of stacked thumbAll Components (possibly breaking)
Update build system we use from a custom babel cli setup to preconstruct.
The previous build system transpiles the code in src directory to dist/esm
and dist/cjs keeping the same file structure. The new build system merges
all files in src and transpiles to a single esm and cjs file.
Potential Breaking Change: The side effect of this is that, if you
imported any function, component or hook using the undocumented approach
like
import { useOutsideClick } from "@chakra-ui/hooks/dist/use-outside-click",
you'll notice that the this doesn't work anymore.
Here's how to resolve it:
// Won't work 🎇
import { useOutsideClick } from "@chakra-ui/hooks/dist/use-outside-click"
// Works ✅
import { useOutsideClick } from "@chakra-ui/hooks"
If this affected your project, we recommend that you import hooks, functions or components the way it's shown in the documentation. This will help keep your project future-proof.
Media Query
Corrected eslint errors.
Fix an issue where the useMediaQuery was not updating the array of booleans
correctly when resizing the viewport.
It also removes deprecated calls addListener and removeListener in favor
of the recommended addEventListener and removeEventListener calls.
Color Mode
Added possibility to use the system preferred color scheme as value for
initialColorMode, while still respecting a user's previous choice.
As long as the user does not manually select a color mode through a website interaction, the theme will change when the system preference changes.
This would easily allow for an implementation where the user can choose
between light, dark and system by simply setting the initialColorMode
setting to system and presenting the user with the three options.
Checkbox, Menu, Modal, Popover, React, Theme, Toast, Tooltip, Transition
framer-motion 5.x in peerDependencyDocs
Add a more detailed explanation on how to style multipart-components
Add new article about multipart components
Popper
[] value for modifiers and moved it into createPopper
definition. This allows memoized modifiers to work correctly in user-land when
used with useCallback.Radio
getRadiopropsDocs
Breadcrumb
href attribute was set on the inner element of the
BreadcrumbLink if the parent BreadcrumbItem has isCurrentPage prop set
to true. Such a BreadcrumbLink is not an actual link and it ends up being a
span (by default).Color Mode
Gatsby Plugin
peerDependencies to include Gatsby 4Hooks, Menu
Menu
Radio
React, Theme Tools, Utils
Slider
Switch
System
useToken where it wasn't possible to resolve some tokens
which contain dots like useToken('space','1.5'). (see #4834)Anatomy, Popover, Theme
Styled System
Checkbox
tabIndex property isn't passed to the underlying input
elementHooks
threshold options from usePanSession to PanSession classModal
closeOnOverlayClick is falsePopover
computePositionOnMount didn't work without explict valueRadio
Button
@chakra-ui/react-utils importCLI
SyntaxError: JSON5: invalid characterToast
useToast and createStandaloneToast to be
discovered by role and accessible name (e.g. using Testing Library
ByRole).Transition
Slider
Move hard-coded styles to slider's theme
Add support for multithumb slider. We now have useRangeSlider, RangeSlider
and RangeSlider* components
<RangeSlider>
<RangeSliderTrack>
<RangeSliderFilledTrack />
</RangeSliderTrack>
<RangeSliderThumb index={0} />
<RangeSliderThumb index={1} />
</RangeSlider>
Theme
Anatomy
Avatar
ignoreFallback, just like you can
with the Image componentButton
Button with framer-motion's motion factory
breaks animation/transitionCheckbox
data-* attributes to the checkbox container to allow user style
the _checked, _invalid and _disabled statesCLI
Fixed an issue where the CLI did not resolve custom tsconfig paths.
🚨 Please note that only the first alias target from the string array will be resolved.
// tsconfig.json
{
//...
compilerOptions: {
baseUrl: "src",
paths: {
"@alias/*": ["target/*"],
// ^-- only the first target will be resolved
},
},
}
Image
onLoad doesn't get called when using srcsetfallbackSrc or a fallback ignoreFallback
is applied by defaultMenu
MenuButton isn't
rendered. This is useful in scenarios where you want the menu to be triggered
by a command or right-click.Provider
ChakraProviderProps type what was removed in previous releaseDocs
Drawer, Modal
start and end
values. The drawer will use left/right placement depending on the specified
theme.direction value.motionPreset prop type since Drawer only implements the Slide
transition, unlike Modal that allows you switch its motion preset.Popper
usePopper now accepts a direction prop so it can handle placement for RTL
languages. Values such as top-start, top-end, bottom-start and
bottom-end will be flipped depending on the theme's direction value.Slider
RTL support by using the theme's direction ("ltr" or "rtl") to set the
default isReversed property when the orientation is horizontalToast
position values. You can now use top-start,
top-end, bottom-start and bottom-end values. The toast will flip
depending on the direction provided in the theme.Drawer, Modal
motionPreset prop type since Drawer only implements the Slide
transition, unlike Modal that allows you switch its motion preset.Select
SelectIcon can be reflected by a disabled
FormControl or by the isDisabled-flag of the select fieldTheme, Theme Tools
tinycolor2 with @ctrl/tinycolor to get better tree-shaking
benefitsDocs
Layout
LinkBox componentSkeleton
Slider
onChangeEnd changes.onChangeStart/ onChangeEnd when clicking somewhere in the
SliderTrack without dragging the DragHandleDocs
Hooks
useOutsideClick hook to conditionally attach
event handlers.Radio
isDisabled to RadioGroup to make it possible to disable all Radio
inside RadioGroupisFocusable to RadioGroup to make it possible to define the
focusable-state for all Radio inside a RadioGroupTheme
overview:"visible" to baseStyle of TagLabel to avoid clipped textTheme Tools
Add new helpers to the theme-tools package to make the process of creating
component themes less cumbersome.
cssVar - function to create css varscalc - function that makes it easy to create the css calc stringanatomy- function to define and extend component partsCreating a CSS variable in the theme
import { cssVar, calc } from "@chakra-ui/theme-tools"
const $width = cssVar("slider-width")
const $height = cssVar("slider-height")
const $diff = calc($width).subtract($height).toString()
$width.variable // => '--slider-width'
$width.reference // => 'var(--slider-width)'
Create a component anatomy
import { anatomy } from "@chakra-ui/theme-tools"
import type { PartsStyle } from "@chakra-ui/theme-tools"
const btn = anatomy("button").parts("label", "container")
const newBtn = btn.extend("icon") // extend button to include icon part
// Using the anatomy in component theme
const baseStyle: PartsStyle<typeof newBtn> = {
// auto-complete for the component parts
icon: {...},
label: {...}
}
Added PartsStyleObject and PartStyleFunction types for easy creation of
type-safe, multipart component styles.
Toast
UseToastOptionsDocs
Hooks
useMenu hook to only enable the useOutsideClick hook when the
menu is open.Provider
@chakra-ui/providerReact
Move ChakraProvider to a separate package @chakra-ui/provider
Loosen types of extendTheme to allow recent TS compiler to work and avoid
Type instantiation is excessively deep and possibly infinite errors.
This might lead to a slightly degraded autocomplete experience when extended the theme but we promise to revisit the typings and API very soon.
In the meantime, please use
ThemeOverridestype to provide
System
useStyleConfig to read parts array from the new anatomy classButton
Button in loading state didn't consider the width
of leftIcon and rightIcon, resulting in layout shifts when the button
leaves the loading state. Buttons now render with the same width regardless of
state.Checkbox
Form Control
aria-describedby property is being overwritten.Layout
Menu
Number Input, Radio
Slider
Styled System
Corrected parseGradient function so that it checks for CSS functions.
Previously, using the CSS calc function would result in invalid CSS being
generated.
The expectation is that
<Heading bgGradient="linear(to-r, green.200, pink.500 calc(20px + 20px))">
Chakra-UI: Create accessible React apps with speed
</Heading>
functions similar to linear-gradient which handles using a CSS function
<Heading
bgImage="linear-gradient(
to right,
var(--chakra-colors-green-200)),
var(--chakra-colors-pink-500 calc(20px + 20px))"
>
Chakra-UI: Create accessible React apps with speed
</Heading>
Grid props type definitions now correctly reflect the implemented behavior in regard to tokens.
System
Fix type definitions for apply prop.
The apply prop supports responsive styles:
// Before: type error, expects `string` for `apply`
<Text apply={{ sm: 'styles.h3', lg: 'styles.h4' }}>
// After: no type error, expects `ResponsiveValue<string>` for `apply`
<Text apply={{ sm: 'styles.h3', lg: 'styles.h4' }}>
Tooltip
Utils
Form Control, Theme
Added a container part to the FormControl component theme, allowing the
root FormControl element to be themed.
import { extendTheme } from "@chakra-ui/react"
export const theme = extendTheme({
components: {
Form: {
variants: {
// create a variant named "custom"
custom: {
// style the root `FormControl` element
container: {
color: "white",
bg: "blue.900",
},
},
},
},
},
})
Stat, Theme
container-part to Stat styleConfigDocs
next-mdx-enhanced to next-mdx-remotemdx before rendering instead of rendered
React.ElementgetUserData generation if there is an author mentioned in
frontmatter because we partially ran into rate limits from octokit/rest but
didn't used the data at allTheme
size:full have no vertical marginCLI
tokens commands doesn't work with esModuleInteropSystem
borderRadius) would not
fallback to the default stylesUtils
rollup.Menu
closeOnSelect won't work sometimesToast
overflowX couldn't be used within a toast's title
or description by adding maxWidth="100%" to the containing div.Button
className prop to button spinnerMedia Query
useBreakpointValue() now supports receiving a defaultBreakpoint as the
second argument to support SSR/SSG.Menu, Popover
computePositionOnMount prop to allow positioning the popover or menu
before initial openSystem
Added the _activeStep pseudoselector which is applied when
aria-current="step".
See the wai-aria documentation
for more information on aria-current.
The styled function allows a functional baseStyle property:
import { styled } from '@chakra-ui/react'
const MyComponent = styled('div', {
baseStyle: (props) => ({
bg: props.highlightColor
})
})
// ...
<MyComponent highlightColor="red.500" />
CLI
The tokens command now supports generating theme token type definitions from a
Chakra UI theme published as a package:
npx @chakra-ui/cli tokens <@your-org/chakra-theme-package>
A published theme package should export a theme object as either the default
export or an export named theme.
// chakra-theme-package/src/index.js
import { extendTheme } from "@chakra-ui/react"
const theme = extendTheme({})
// as default export
export default theme
// as named export
export { theme }
System
bgImage urlPopper
Add enabled option to usePopper hook. The popper.js instance will not be
created until this option is true.
Menu, Popover and Tooltip components now use this option, so the
popper.js instance is created only once the popper is open. This should
significantly improve render and scroll performance.
Affect components:
Popover,Menu,Tooltip
Form Control
FormLabel could not be used without form-controlMenu
isLazy is passed.NumberInput
allowMouseWheel is passedRadio
Radio or useRadio gets non-unique id when wrapped within
FormControl.Transition
onAnimationComplete is not forwarded to motion elementGatsby Plugin
pluginOptions correctly to the ChakraProvider. FixesChakraProvider
ChakraProvider now accepts the prop cssVarsRoot which defaults to
:host, :root.System
Added ring style props to make it easier to style an element's focus ring
shadows. Props are ring, ringColor, ringOffset, and ringOffsetColor.
// adds a 2px box-shadow with `gray.400` color
<Box ring="2px" ringColor="gray.400">
Sample
</Box>
// adds main box-shadow + offset box-shadow
<Box ring="2px" ringColor="gray.400" ringOffset="3px" ringOffsetColor="white">
Sample
</Box>
Added css variable based API to apply css filter properties (blur,
backdrop-blur) to an element. Props are filter, blur, sepia, brightness,
invert, saturation, backdropFilter, backdropBlur, sepia, saturation,
etc.
To use this API, you'll need to set filter to auto, same for
backdropFilter.
// adds a 3px blur filter to this element
<Image src="boruto.png" filter="auto" blur="3px" />
// adds a 3px blur and 40% saturation filter to this element
<Image src="boruto.png" filter="auto" blur="3px" saturation={0.4} />
Added css variable based API to apply css transform properties (translateX,
translateY, scale, etc.). Props are translateX, translateY, rotate,
scaleX, scaleY, and scale.
To use this API, you'll need to set transform to auto or auto-gpu (for the
GPU accelerated version).
<Circle transform="auto" translateX="4" _hover={{ translateX: "8" }}>
<CheckIcon />
</Circle>
Add mixBlendMode, backgroundBlendMode, and bgBlendMode props to apply
blend modes to elements
Automatic wrapping of backgroundImage or bgImage props with url() so you
can just pass the image URL directly.
// You can now do this!
<Box bgImage="naruto.png" />
// This still works
<Box bgImage="url(naruto.png)" />
text decoration styles: Added textDecorationColor, textDecorationLine,
textDecorationStyles style props.
Add isolation style prop to create a new stacking context.
Add support for High Contrast Mode
Fixed issue where setting outline:0 or outline:none and using box-shadow
for focus outlines don't work in high-contrast mode. To fix this, we've added
outline: 2px solid transparent whenever you set outline:0 to make your
components work in high-constrast mode by default.
Learn more
Fix the _dark pseudo props to map to
.chakra-ui-dark &, [data-theme=dark] &, &[data-theme=dark].
Added _light pseudo props to map to
.chakra-ui-light &, [data-theme=light] &, &[data-theme=light] for users that
prefer to start with dark mode.
Added overscroll, overscrollX, and overscrollY style prop to manage
overscroll behavior of an container
Theme
filter and backdropFilter{
"none": 0,
"sm": "4px",
"base": "8px",
"md": "12px",
"lg": "16px",
"xl": "24px",
"2xl": "40px",
"3xl": "64px"
}
ChakraProvider
:host, :root to fix usage in shadow dom.Slider
onChangeStart doesnt get calledisDisabled={true}onChangeEnd doesn't get called when you click anywhere on
the trackCLI
Fixes issues with tokens command hanging forever if theme workers run into
errors during runtime.
Now when an error is discovered within a worker an { err: string } object is
passed to the parent which will cause the promise to reject.
This will in turn, pass the same err upwards to allow the command to exit
gracefully, printing the err in question to stdout
Popover
usePopoverContext hookTransition
Add support for tweaking the enter-exit transitions.
Affected components:
Fade,Slide,SlideFade,SlideScale,Collapse
<Fade
transition={{
enter: { duration: 0.3 },
exit: { duration: 0.1 },
}}
/>
Collapse animation hide overflow when it expands.Collapse transition how shows overflow when it's expanded and hides overflow when it's collapsed.
delay prop for all transition components.// as a number
<Fade delay={0.3} />
// or based on state (enter/exit only)
<Fade delay={{ enter: 0.2 }} />
// or both
<Fade delay={{ enter: 0.2, exit: 0.1 }} />
Note: this only works when you're using our built-in transition definition. If you're passing your own transition definition, pass the delay there.
// adding delay to your custom transition definition
<Fade
transition={{
enter: { duration: 0.2, delay: 0.1 },
}}
/>
Tabs
System
Add new extendTheme function that allows you to pass multiple overrides or
extensions:
import {
extendTheme,
withDefaultColorScheme,
withDefaultSize,
withDefaultVariant,
withDefaultProps,
} from "@chakra-ui/react"
const customTheme = extendTheme(
{
colors: {
brand: {
// ...
500: "#b4d455",
// ...
},
},
},
withDefaultColorScheme({ colorScheme: "brand" }),
withDefaultSize({
size: "lg",
components: ["Input", "NumberInput", "PinInput"],
}),
withDefaultVariant({
variant: "outline",
components: ["Input", "NumberInput", "PinInput"],
}),
// or all in one:
withDefaultProps({
defaultProps: {
colorScheme: "brand",
variant: "outline",
size: "lg",
},
components: ["Input", "NumberInput", "PinInput"],
}),
// optional:
yourCustomBaseTheme, // defaults to our chakra default theme
)
Gatsby Plugin
Upgrading to this new major version is recommended for everyone as it fixes hot
reloading in Gatsby (Fast Refresh). In the previous version changes to the
shadowed theme.js file didn't trigger automatic reloading, and a manual reload
was necessary.
Breaking Changes
isUsingColorMode option was removed. The ChakraProvider will always
use the ColorModeProviderisResettingCSS option was renamed to resetCSSImprovements
ChakraProvider instead of the outdated ThemeProvider patterninitialColorMode to the ColorModeScriptpeerDependency on gatsby (to ^2.29.3 || ^3.0.0)Modal
Slider
Stat
StatHelpText. It was using an invalid dl child
tag.System
Button
spinnerPlacement prop to allow changing the spinner placement for the
button when isLoading is true. Spinner placement can be either start or
end<Button isLoading spinnerPlacement="end">
Click me
</Button>
Checkbox
isDisabled prop to CheckboxGroupMenu, Popover, Tabs
Revert the behavior of the isLazy prop (which was broken by the previous
release) and adds a new lazyBehavior prop which configures the behavior of
isLazy.
If you'd like the content of tab panel, popover and menu components to be
unmounted when not selected or opened, please continue to use isLazy. This
is the default behavior.
If you'd like the content of tab panel, popover and menu components to remain
mounted (but hidden) after it was previously selected or opened, use
lazyBehavior="keepMounted" in combination with isLazy.
Menu, Popover
List
OrderedList and UnorderedListProgress
CircularProgress with isIndeterminate doesn't show the
indicatorSystem
extendTheme where variant overrides lead to an TS
error.Spinner
Menu
Add closeOnSelect to MenuItem and MenuItemOption.
This allows menu items to override their parent Menu's closeOnSelect
behavior.
Can be useful for menus with a combination of MenuItems (that generally
close their menu when selected) and MenuItemOptions (that should keep the
menu open for further edition).
Fix issue where menu unmounts after first render
Environment
EnvironmentProvider to ChakraProvider for better window and document
detection across hooks and componentsSystem
useStyleConfig hookTabs
Theme
panel part name in Progress theme file to labelTable
TableContainer component to help tables scroll horizontally when
overflowing.<TableContainer>
<Table>{...}</Table>
</TableContainer>
Popover
ref callback to
determine element's presense instead of useEffect.usePopover as internal for now.rootProps to PopoverContent to allow passing props to
popover's positioner.variants so users can orchestrate
custom transitions.maxW from popover's popper to content to allow for better control
of the popover's width.width instead of maxW to allow users more control of popover's width--popover-bg css property to control popover and arrow background.<PopoverContent style={{ "--popover-bg": "purple" }}>
<PopoverArrow />
</PopoverContent>
Select
insetEnd instead of right for RTL.Skip Link
insetStart instead of left for RTL.Table
end instead of right for RTL.Hooks
useControllableState: The onChange callback will be called only if the new
value isn't equal to the current one.`Stack
AbsoluteCenter
position: absoluteNumberInput
aria-* props to the input element.onChange was called on mount.onBlur was called twice.onFocus, onBlur, getAriaValueTextuseFormControl logic to be called from NumberInput
instead.setFocused.on with ReactDOM.flushSync to prevent concurrent mode
issue where setting state in onFocus affects onChange event handler.Form Control
useFormControl hook that returns prop getters getHelpTextProps,
getErrorMessageProps, and getRootProps. This will make it easier to
integrate with number-input, checkbox, and switch.withFlushSync helper to achieve this.System
// We're convert `colors.red.200` to `var(--chakra-colors-red-200)`
<Box
sx={{
"--banner-color": "colors.red.200",
"& .banner": {
bg: "var(--banner-color)",
},
}}
/>
You can also add fallback values in event the token doesn't exist:
<Box
sx={{
// evaluates to #fff if `colors.red.1000` doesn't exists in theme map
"--banner-color": "colors.red.1000, #fff",
"& .banner": {
bg: "var(--banner-color)",
},
}}
/>
This opens new possbilities with css variables, for example you can apply responsive token values like you would with style props.
TypeScript support for this is still WIP
<Box
sx={{
"--banner-color": ["colors.red.200", "colors.pink.400"],
"& .banner": {
bg: "var(--banner-color)",
},
}}
/>
rotateX, rotateY, scaleX, scaleY style props.Theme
0 token value from spacing tokens. 0 maps to 0 and there's no need
to create a css custom property for that.System :Avoid mutation for getWithPriority to get textStyle and
layerStyle working consistently.
All Components
framer-motion v4System
toCSSVars omitted the transition tokensconfig.property
mutation.mx and px to use logical properties. Instead of mapping to
marginLeft and marginRight, it maps to marginInlineStart and
marginInlineEnd. Same for pxRadio
onChange type for use-radio-group propsTag
aria-label to tag close buttonTagLeftIcon and TagRightIcon doesn't work for RTL layouts.Hooks
usePointerEvent hook to unify pointer event managementuseFocusOnPointerDown to get Safari to detect the correct
event.relatedTarget when you blur a focused element.CLI
textStyle and layerStyle theme type generation to
@chakra-ui/cliSystem
textStyle and layerStyle theme type generation to
@chakra-ui/cliTheme
root to parts to NumberInput theme, leverage css variables and update
styles to be rtl friendly.Popper (Breaking)
Refactor the positioning logic to improve stability and leverage CSS custom properties
Refactor arrow components to use data-popper-arrow and
data-popper-arrow-inner to define the arrow elements. This is used within
the modifiers to update the arrow styles/position positioning.
Change arrowSize and arrowShadowColor to use CSS custom properties instead
of passing it to usePopper.
Update component themes to use --popper-arrow-bg to set the background for
the popper's arrow element.
All Components
strictNullChecks: false in tsconfig.json lead to an error.Tabs
TabPanels component can now be styled from Tabs component theme,
specifying the tabpanels part.Theme
optgroup in dark mode was unreadable on browsers
that allow select contents styling.Popper
System
Improve style computation performance by 2.5x by converting all theme tokens to CSS variables. This also makes it possible to reference theme tokens in vanilla CSS as well.
Add new config property cssVarPrefix to add a custom prefix for CSS
variables. It defaults to chakra.
Adds support for main element in chakra factory
Popper
CLI
tokens command now ignores TS errors in your theme.ts fileColor Mode
nonce of the <script> that
ColorModeScript creates by passing nonce prop.Checkbox, Radio
label is a phrasing content
element and should not contain block element div.div with span which is an inline element.Focus Lock: Upgrade to [email protected] and
[email protected] to fix React 17 peer dependencies compatibility
System
extendTheme function uses the type Theme againdefaultProps and
ComponentMultiStyleConfig were too narrow.System: Fix issue wher typings for size and variant for AvatarGroup,
CheckboxGroup, ButtonGroup, and RadioGroup were incorrect.
PinInput
Resolved an issue where completing character entry in PinInput failed to call
onComplete.
System
Fixed issue in extendTheme where overrides defined as function replaced all
base styles defined as plain object.
Allow numbers for borderTop and provide autocomplete for fontWeight prop
Tooltip
Tooltip with negative gutter causes flickering on
hover.System
ChakraTheme to improve the extendTheme function
even furtherimport { extendTheme } from "@chakra-ui/react"
export const customTheme = extendTheme({
// here you get autocomplete for
// - existing definitions from the default theme
// - new components (Single and MultiStyle)
// - CSS definitions
// - color hues
// - etc.
})
export type MyCustomTheme = typeof customTheme
You can get typesafe access to your custom theme like this:
import { useTheme } from "@chakra-ui/react"
import { MyCustomTheme } from "./my-custom-theme"
const MyComponent = () => {
const customTheme = useTheme<MyCustomTheme>()
//...
}
textStyle and layerStyle in styled-system package. This
makes it possible to use them in the component theme, css function, and sx
prop as well.const theme = {
textStyles: {
caps: {
fontWeight: "bold",
fontSize: "24px",
},
},
}
const styles = css({ textStyle: "caps" })(theme)
This also works for component theme as well.
layerStyle,textStyleandapplycan now take responsive values as well.
apply prop handling to use the style config pattern instead of
add it imperatively.System: Allow string values for ThemingProps['colorScheme']
CLI: Add support for tokens command to generate theme typings.
AbsoluteCenter: Fix issue where style was incorrect when when axis is
both
NumberInput: Fix issue where blurring NumberInputField did not clamp the
value using the precision prop
Styled System
_hover and _active didn't
allow standard CSS propertiesStack: Add shouldWrapChildren to Wrap component to make it possible use
Wrap directly without thinking about WrapItem.
Menu
rootProps to MenuList so it's possible override the styles for
root container for menu list. Common use case is to change the applied
zIndex of the menulist.zIndex by passing props to MenuListMenuItem now accepts a commandSpacing prop that can be used to adjust
the space between the command and label.Portal
containerRef to portal.appendToParentPortal={false} to opt out of nested portals.zIndex container where it renders elements outside of
view.getContainer prop to containerRef to make it possible to pass the
ref directly. This affects the Modal component primarily// Before
<Portal getContainer={() => ref.current}></Portal>
// After
<Portal containerRef={ref}></Portal>
Modal, Tooltip
Add support for forwarding props to the underlying Portal component. Pass the
portalProps prop to achive this. The 2 props you can pass to the portalProps
are:
containerRef: ref for the element where to mount the portalappendToParentPortal: If false, it'll opt out of portal nesting<Modal portalProps={{ containerRef: ref }}>
<ModalOverlay />
<ModalContent>
<Box>Modal content</Box>
<Tooltip portalProps={{ appendToParentPortal: false }}>
Some tooltip
</Tooltip>
</ModalContent>
</Modal>
Color Mode: useColorModeValue defaults to light mode on first render if
system color mode is used.
Hooks: Update useOutsideClick reference to use the correct owner document