url
stringlengths
17
87
content
stringlengths
152
81.8k
https://www.chakra-ui.com/docs/theming/recipes
1. Concepts 2. Recipes # Recipes Writing multi-variant styles with recipes in Chakra. ## [Overview]() Chakra provides a way to write CSS-in-JS with better performance, developer experience, and composability. One of its key features is the ability to create multi-variant styles with a type-safe runtime API. A recipe consists of these properties: - `className`: The className to attach to the component - `base`: The base styles for the component - `variants`: The different visual styles for the component - `compoundVariants`: The different combinations of variants for the component - `defaultVariants`: The default variant values for the component ## [Defining the recipe]() Use the `defineRecipe` identity function to create a recipe. button.recipe.ts ``` import { defineRecipe } from "@chakra-ui/react" export const buttonRecipe = defineRecipe({ base: { display: "flex", }, variants: { visual: { solid: { bg: "red.200", color: "white" }, outline: { borderWidth: "1px", borderColor: "red.200" }, }, size: { sm: { padding: "4", fontSize: "12px" }, lg: { padding: "8", fontSize: "24px" }, }, }, }) ``` ## [Using the recipe]() There are two ways to use the recipe in a component: - Directly in the component with `useRecipe` - Creating a component (recommended) with the `chakra` factory info **RSC Tip:** Adding the `"use client"` directive is required since it relies on react hooks like `useContext` and `useInsertionEffect` under the hood. ### [Directly in component]() Use the `useRecipe` hook to get the recipe for a component. Then, call the recipe with its variant props to get the styles. button.tsx ``` "use client" import { chakra, useRecipe } from "@chakra-ui/react" import { buttonRecipe } from "./button.recipe" export const Button = (props) => { const { visual, size, ...restProps } = props const recipe = useRecipe({ recipe: buttonRecipe }) const styles = recipe({ visual, size }) return <chakra.button css={styles} {...restProps} /> } ``` #### [splitVariantProps]() Notice how the `visual` and `size` props were destructured from the props to be passed to the recipe. A smarter approach would be to automatically split the recipe props from the component props. To do that, use the `recipe.splitVariantProps` function to split the recipe props from the component props. button.tsx ``` "use client" import { chakra, useRecipe } from "@chakra-ui/react" import { buttonRecipe } from "./button.recipe" export const Button = (props) => { const recipe = useRecipe({ recipe: buttonRecipe }) const [recipeProps, restProps] = recipe.splitVariantProps(props) const styles = recipe(recipeProps) // ... } ``` #### [TypeScript]() To infer the recipe variant prop types, use the `RecipeVariantProps` type helper. button.tsx ``` import type { RecipeVariantProps } from "@chakra-ui/react" import { buttonRecipe } from "./button.recipe" type ButtonVariantProps = RecipeVariantProps<typeof buttonRecipe> export interface ButtonProps extends React.PropsWithChildren<ButtonVariantProps> {} ``` ### [Creating a component]() Use the `chakra` function to create a component from a recipe. **Note:** The recipe can also be inlined into the `chakra` function. button.tsx ``` "use client" import { chakra } from "@chakra-ui/react" import { buttonRecipe } from "./button.recipe" export const Button = chakra("button", buttonRecipe) ``` Next, use the component and pass recipe properties to it. app.tsx ``` import { Button } from "./button" const App = () => { return ( <Button visual="solid" size="lg"> Click Me </Button> ) } ``` ## [Default Variants]() The `defaultVariants` property is used to set the default variant values for the recipe. This is useful when you want to apply a variant by default. button.tsx ``` "use client" import { chakra } from "@chakra-ui/react" const Button = chakra("button", { base: { display: "flex", }, variants: { visual: { solid: { bg: "red.200", color: "white" }, outline: { borderWidth: "1px", borderColor: "red.200" }, }, size: { sm: { padding: "4", fontSize: "12px" }, lg: { padding: "8", fontSize: "24px" }, }, }, defaultVariants: { visual: "solid", size: "lg", }, }) ``` ## [Compound Variants]() Use the `compoundVariants` property to define a set of variants that are applied based on a combination of other variants. button.tsx ``` "use client" import { chakra } from "@chakra-ui/react" const button = cva({ base: { display: "flex", }, variants: { visual: { solid: { bg: "red.200", color: "white" }, outline: { borderWidth: "1px", borderColor: "red.200" }, }, size: { sm: { padding: "4", fontSize: "12px" }, lg: { padding: "8", fontSize: "24px" }, }, }, compoundVariants: [ { size: "small", visual: "outline", css: { borderWidth: "2px", }, }, ], }) ``` When you use the `size="small"` and `visual="outline"` variants together, the `compoundVariants` will apply the `css` property to the component. app.tsx ``` <Button size="small" visual="outline"> Click Me </Button> ``` ## [Theme Usage]() To use the recipe in a reusable manner, move it to the system theme and add it to `theme.recipes` property. theme.ts ``` import { createSystem, defineConfig } from "@chakra-ui/react" import { buttonRecipe } from "./button.recipe" const config = defineConfig({ theme: { recipes: { button: buttonRecipe, }, }, }) export default createSystem(config) ``` ### [TypeScript]() Use the CLI to generate the types for the recipe. ``` npx @chakra-ui/cli typegen ./theme.ts ``` Then, import the generated types in your component. button.tsx ``` import type { RecipeVariantProps } from "@chakra-ui/react" import { buttonRecipe } from "./button.recipe" type ButtonVariantProps = RecipeVariantProps<typeof buttonRecipe> export interface ButtonProps extends React.PropsWithChildren<ButtonVariantProps> {} ``` ### [Update code]() If you use the recipe directly in your component, update the `useRecipe` to use the `key` property to get the recipe from the theme. button.tsx ``` const Button = () => { - const recipe = useRecipe({ recipe: buttonRecipe }) + const recipe = useRecipe({ key: "button" }) // ... } ``` [Previous \ Semantic Tokens](https://www.chakra-ui.com/docs/theming/semantic-tokens) [Next \ Slot Recipes](https://www.chakra-ui.com/docs/theming/slot-recipes)
https://www.chakra-ui.com/docs/theming/semantic-tokens
1. Concepts 2. Semantic Tokens # Semantic Tokens Leveraging semantic tokens for design decisions in your app. ## [Overview]() Semantic tokens are tokens that are designed to be used in a specific context. A semantic token consists of the following properties: - `value`: The value of the token or a reference to an existing token. - `description`: An optional description of what the token can be used for. ## [Defining Semantic Tokens]() In most cases, the value of a semantic token references to an existing token. To reference a value in a semantic token, use the token reference `{}` syntax. theme.ts ``` import { createSystem, defineConfig } from "@chakra-ui/react" const config = defineConfig({ theme: { tokens: { colors: { red: { value: "#EE0F0F" }, }, }, semanticTokens: { colors: { danger: { value: "{colors.red}" }, }, }, }, }) export default createSystem(config) ``` ## [Using Semantic Tokens]() After defining semantic tokens, we recommend using the Chakra CLI to generate theme typings for your tokens. ``` npx @chakra-ui/cli typegen ./src/theme.ts ``` This will provide autocompletion for your tokens in your editor. ``` <Box color="danger">Hello World</Box> ``` ## [Conditional Token]() Semantic tokens can also be changed based on the conditions like light and dark modes. For example, if you want a color to change automatically based on light or dark mode. theme.ts ``` import { createSystem, defineConfig } from "@chakra-ui/react" const config = defineConfig({ theme: { semanticTokens: { colors: { danger: { value: { base: "{colors.red}", _dark: "{colors.darkred}" }, }, success: { value: { base: "{colors.green}", _dark: "{colors.darkgreen}" }, }, }, }, }, }) export default createSystem(config) ``` info The conditions used in semantic tokens must be an at-rule or parent selector [condition](https://www.chakra-ui.com/docs/styling/conditional-styles). ## [Semantic Token Nesting]() Semantic tokens can be nested to create a hierarchy of tokens. This is useful when you want to group tokens together. info Use the `DEFAULT` key to define the default value of a nested token. theme.ts ``` import { createSystem, defineConfig } from "@chakra-ui/react" const config = defineConfig({ theme: { semanticTokens: { colors: { bg: { DEFAULT: { value: "{colors.gray.100}" }, primary: { value: "{colors.teal.100}" }, secondary: { value: "{colors.gray.100}" }, }, }, }, }, }) export default createSystem(config) ``` This allows the use of the `bg` token in the following ways: ``` <Box bg="bg"> <Box bg="bg.primary">Hello World</Box> <Box bg="bg.secondary">Hello World</Box> </Box> ``` [Previous \ Tokens](https://www.chakra-ui.com/docs/theming/tokens) [Next \ Recipes](https://www.chakra-ui.com/docs/theming/recipes)
https://www.chakra-ui.com/docs/theming/slot-recipes
1. Concepts 2. Slot Recipes # Slot Recipes Learn how to style multiple parts components with slot recipes. ## [Overview]() Slot Recipes come in handy when you need to apply style variations to multiple parts of a component. A slot recipe consists of these properties: - `className`: The className prefix to attach to the component slot - `slots`: An array of component parts to style - `base`: The base styles per slot - `variants`: The different visual styles for each slot - `defaultVariants`: The default variant for the component - `compoundVariants`: The compound variant combination and style overrides for each slot. ## [Defining the recipe]() Use the `defineSlotRecipe` identity function to create a slot recipe. checkbox.recipe.ts ``` import { defineSlotRecipe } from "@chakra-ui/react" export const checkboxSlotRecipe = defineSlotRecipe({ slots: ["root", "control", "label"], base: { root: { display: "flex", alignItems: "center", gap: "2" }, control: { borderWidth: "1px", borderRadius: "sm" }, label: { marginStart: "2" }, }, variants: { size: { sm: { control: { width: "8", height: "8" }, label: { fontSize: "sm" }, }, md: { control: { width: "10", height: "10" }, label: { fontSize: "md" }, }, }, }, }) ``` ## [Using the recipe]() There are two ways to use the recipe in a component: - Directly in the component with `useSlotRecipe` - As a compound component (recommended) with `createSlotRecipeContext` info Adding the `"use client"` directive is required to use the `useSlotRecipe` hook or `createSlotRecipeContext` function. This is because they rely on react hooks like `useContext` and `useInsertionEffect` under the hood. ### [Directly in component]() Use the `useSlotRecipe` hook to get the recipe for a component. Then, call the recipe with its variant props to get the styles. checkbox.tsx ``` "use client" import { chakra, useSlotRecipe } from "@chakra-ui/react" import { checkboxSlotRecipe } from "./checkbox.recipe" export const Checkbox = (props) => { const { size, ...restProps } = props const recipe = useSlotRecipe({ recipe: checkboxSlotRecipe }) const styles = recipe({ size }) return ( <chakra.label css={styles.root}> <chakra.input type="checkbox" css={styles.control} {...restProps} /> <chakra.span css={styles.label}>Checkbox Label</chakra.span> </chakra.label> ) } ``` #### [splitVariantProps]() Notice how the `size` prop was destructured from the props to be passed to the recipe. A smarter approach would be to automatically split the recipe props from the component props. To do that, use the `recipe.splitVariantProps` function to split the recipe props from the component props. checkbox.tsx ``` "use client" import { chakra, useSlotRecipe } from "@chakra-ui/react" import { checkboxSlotRecipe } from "./checkbox.recipe" export const Checkbox = (props) => { const recipe = useSlotRecipe({ recipe: checkboxSlotRecipe }) const [recipeProps, restProps] = recipe.splitVariantProps(props) const styles = recipe(recipeProps) //... } ``` #### [TypeScript]() To infer the recipe variant prop types, use the `RecipeVariantProps` type helper. checkbox.tsx ``` import type { RecipeVariantProps } from "@chakra-ui/react" import { checkboxSlotRecipe } from "./checkbox.recipe" type CheckboxVariantProps = RecipeVariantProps<typeof checkboxSlotRecipe> export interface CheckboxProps extends React.PropsWithChildren<CheckboxVariantProps> {} ``` ### [Create compound components]() Pass the recipe to the `createSlotRecipeContext` function to create a slot recipe context. Then, use the `withProvider` and `withContext` functions to create the compound components that share the same context. info You will need to manually type the generics for `withProvider` and `withContext`. This approach is designed to optimize TypeScript performance. Auto-inference, while convenient, would slow down TypeScript compilation due to the complexity of the types involved. checkbox.tsx ``` "use client" import { createSlotRecipeContext } from "@chakra-ui/react" import { checkboxSlotRecipe } from "./checkbox.recipe" const { withProvider, withContext } = createSlotRecipeContext({ recipe: checkboxSlotRecipe, }) interface CheckboxRootProps extends HTMLChakraProps< "label", RecipeVariantProps<typeof checkboxSlotRecipe> > {} export const CheckboxRoot = withProvider<HTMLLabelElement, CheckboxRootProps>( "label", "root", ) interface CheckboxControlProps extends HTMLChakraProps<"input"> {} export const CheckboxControl = withContext< HTMLInputElement, CheckboxControlProps >("input", "control") interface CheckboxLabelProps extends HTMLChakraProps<"span"> {} export const CheckboxLabel = withContext<HTMLSpanElement, CheckboxLabelProps>( "span", "label", ) ``` Pass the variant props to the "root" component that to apply the styles. **Note:** The root component is the one that used the `withProvider` function. app.tsx ``` const App = () => { return ( <CheckboxRoot size="md"> <CheckboxControl /> <CheckboxLabel /> </CheckboxRoot> ) } ``` #### [unstyled prop]() This approach supports the use of the `unstyled` prop to remove the styles applied by the recipe. checkbox.tsx ``` <CheckboxRoot unstyled> <CheckboxControl /> <CheckboxLabel /> </CheckboxRoot> ``` #### [TypeScript]() To infer the recipe variant prop types, use the `RecipeVariantProps` type helper. ``` import type { RecipeVariantProps, UnstyledProp } from "@chakra-ui/react" import { checkboxSlotRecipe } from "./checkbox.recipe" type CheckboxVariantProps = RecipeVariantProps<typeof checkboxSlotRecipe> export interface CheckboxProps extends React.PropsWithChildren<CheckboxVariantProps>, UnstyledProp {} ``` ## [Compound Variants]() Use the `compoundVariants` property to define a set of variants that are applied based on a combination of other variants. checkbox.recipe.ts ``` import { defineSlotRecipe } from "@chakra-ui/react" export const checkboxRecipe = defineSlotRecipe({ slots: ["root", "control", "label"], base: {}, variants: { size: { sm: {}, md: {}, }, visual: { contained: {}, outline: {}, }, }, compoundVariants: [ { size: "sm", visual: "outline", css: { control: { borderWidth: "1px" }, label: { color: "green.500" }, }, }, ], }) ``` ## [Targeting a slot]() In some cases, targeting a slot by className might be needed. - Set the `className` property in the config - The naming convention is `${className}__${slot}` checkbox.recipe.ts ``` import { defineSlotRecipe } from "@chakra-ui/react" export const checkboxRecipe = defineSlotRecipe({ className: "checkbox", slots: ["root", "control", "label"], base: { root: { bg: "blue.500", _hover: { "& .checkbox__label": { color: "white" }, }, }, }, }) ``` ## [Theme Usage]() To use the recipe in a reusable manner, move it to the system theme and add it to `theme.slotRecipes` property. No need to add the `"use client"` directive when using the recipe in the theme. theme.ts ``` import { createSystem, defineConfig } from "@chakra-ui/react" import { checkboxSlotRecipe } from "./checkbox.recipe" const config = defineConfig({ theme: { slotRecipes: { checkbox: checkboxSlotRecipe, }, }, }) export default createSystem(config) ``` ### [TypeScript]() Use the CLI to generate the types for the recipe. ``` npx @chakra-ui/cli typegen ./theme.ts ``` Then, import the generated types in your component. checkbox.tsx ``` import type { SlotRecipeProps, UnstyledProp } from "@chakra-ui/react" export interface CheckboxProps extends SlotRecipeProps<"checkbox">, UnstyledProp {} ``` ### [Update code]() If you use the recipe directly in your component, update the `useRecipe` to use the `key` property to get the recipe from the theme. checkbox.tsx ``` const Checkbox = () => { - const recipe = useRecipe({ recipe: checkboxRecipe }) + const recipe = useRecipe({ key: "checkbox" }) // ... } ``` If you create a compound component, update the `createSlotRecipeContext` to use the `key` property. checkbox.tsx ``` const { withProvider, withContext } = createSlotRecipeContext({ - recipe: checkboxRecipe, + key: "checkbox", }) ``` [Previous \ Recipes](https://www.chakra-ui.com/docs/theming/recipes) [Next \ Animations](https://www.chakra-ui.com/docs/theming/animations)
https://www.chakra-ui.com/docs/theming/tokens
1. Concepts 2. Tokens # Tokens Managing design decisions in your app using tokens. ## [Overview]() Design tokens are the platform-agnostic way to manage design decisions in your application or website. It is a collection of attributes that describe any fundamental/atomic visual style. Each attribute is a key-value pair. Design tokens in Chakra are largely influenced by the [W3C Token Format](https://tr.designtokens.org/format/). A design token consists of the following properties: - `value`: The value of the token. This can be any valid CSS value. - `description`: An optional description of what the token can be used for. ## [Defining Tokens]() Tokens are defined in the under the `theme` key in your system config. theme.ts ``` import { createSystem, defineConfig } from "@chakra-ui/react" const config = defineConfig({ theme: { tokens: { colors: { primary: { value: "#0FEE0F" }, secondary: { value: "#EE0F0F" }, }, fonts: { body: { value: "system-ui, sans-serif" }, }, }, }, }) export const system = createSystem(config) ``` warning Token values need to be nested in an object with a `value` key. This is to allow for additional properties like `description` and more in the future. ## [Using Tokens]() After defining tokens, we recommend using the Chakra CLI to generate theme typings for your tokens. ``` npx @chakra-ui/cli typegen ./src/theme.ts ``` This will provide autocompletion for your tokens in your editor. ``` <Box color="primary" fontFamily="body"> Hello World </Box> ``` ### [Token reference syntax]() Chakra UI enables you to reference design tokens within composite values for CSS properties like `border`, `padding`, and `box-shadow`. This is achieved through the token reference syntax: `{path.to.token}`. note It is important to use the complete token path; for example, instead of using `red.300`, you must reference it as `colors.red.300`. Here’s an example where token reference syntax is applied to both the border and p (padding) props: ``` <Box border="1px solid {colors.red.300}" p="{spacing.4} {spacing.6} {spacing.8} {spacing.10}" boxShadow="{spacing.4} {spacing.2} {spacing.2} {colors.red.300}" /> ``` ## [Token Nesting]() Tokens can be nested to create a hierarchy of tokens. This is useful when you want to group related tokens together. info Use the `DEFAULT` key to define the default value of a nested token. theme.ts ``` import { defineConfig } from "@chakra-ui/react" const config = defineConfig({ theme: { tokens: { colors: { red: { DEFAULT: { value: "#EE0F0F" }, 100: { value: "#EE0F0F" }, }, }, }, }, }) export default createSystem(config) ``` ``` <Box // 👇🏻 This will use the `DEFAULT` value bg="red" color="red.100" > Hello World </Box> ``` ## [Token Types]() ### [Colors]() Colors have meaning and support the purpose of the content, communicating things like hierarchy of information, and states. It is mostly defined as a string value or reference to other tokens. theme.ts ``` import { defineTokens } from "@chakra-ui/react" const tokens = defineTokens({ colors: { red: { 100: { value: "#fff1f0" }, }, }, }) export default createSystem({ theme: { tokens }, }) ``` ### [Gradients]() Gradient tokens represent a smooth transition between two or more colors. Its value can be defined as a string or a composite value. theme.ts ``` import { defineTokens } from "@chakra-ui/react" const tokens = defineTokens({ gradients: { // string value simple: { value: "linear-gradient(to right, red, blue)" }, // composite value primary: { value: { type: "linear", placement: "to right", stops: ["red", "blue"] }, }, }, }) export default createSystem({ theme: { tokens }, }) ``` ### [Sizes]() Size tokens represent the width and height of an element. Its value is defined as a string. theme.ts ``` import { defineTokens } from "@chakra-ui/react" const tokens = defineTokens({ sizes: { sm: { value: "12px" }, }, }) export default createSystem({ theme: { tokens }, }) ``` Size tokens are typically used in `width`, `height`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight` properties. ### [Spacing]() Spacing tokens represent the margin and padding of an element. Its value is defined as a string. theme.ts ``` import { defineTokens } from "@chakra-ui/react" const tokens = defineTokens({ spacing: { gutter: { value: "12px" }, }, }) export default createSystem({ theme: { tokens }, }) ``` Spacing tokens are typically used in `margin`, `padding`, `gap`, and `{top,right,bottom,left}` properties. ### [Fonts]() Font tokens represent the font family of a text element. Its value is defined as a string or an array of strings. theme.ts ``` import { defineTokens } from "@chakra-ui/react" const tokens = defineTokens({ fonts: { body: { value: "Inter, sans-serif" }, heading: { value: ["Roboto Mono", "sans-serif"] }, }, }) export default createSystem({ theme: { tokens }, }) ``` Font tokens are typically used in `font-family` property. ### [Font Sizes]() Font size tokens represent the size of a text element. Its value is defined as a string. theme.ts ``` import { defineTokens } from "@chakra-ui/react" const tokens = defineTokens({ fontSizes: { sm: { value: "12px" }, }, }) export default createSystem({ theme: { tokens }, }) ``` Font size tokens are typically used in `font-size` property. ### [Font Weights]() Font weight tokens represent the weight of a text element. Its value is defined as a string. theme.ts ``` import { defineTokens } from "@chakra-ui/react" const tokens = defineTokens({ fontWeights: { bold: { value: "700" }, }, }) export default createSystem({ theme: { tokens }, }) ``` Font weight tokens are typically used in `font-weight` property. ### [Letter Spacings]() Letter spacing tokens represent the spacing between letters in a text element. Its value is defined as a string. ``` const tokens = defineTokens({ letterSpacings: { wide: { value: "0.1em" }, }, }) export default createSystem({ theme: { tokens }, }) ``` Letter spacing tokens are typically used in `letter-spacing` property. ### [Line Heights]() Line height tokens represent the height of a line of text. Its value is defined as a string. theme.ts ``` import { defineTokens } from "@chakra-ui/react" const tokens = defineTokens({ lineHeights: { normal: { value: "1.5" }, }, }) export default createSystem({ theme: { tokens }, }) ``` Line height tokens are typically used in `line-height` property. ### [Radii]() Radii tokens represent the radius of a border. Its value is defined as a string. theme.ts ``` import { defineTokens } from "@chakra-ui/react" const tokens = defineTokens({ radii: { sm: { value: "4px" }, }, }) export default createSystem({ theme: { tokens }, }) ``` Radii tokens are typically used in `border-radius` property. ### [Borders]() A border is a line surrounding a UI element. You can define them as string values or as a composite value theme.ts ``` import { defineTokens } from "@chakra-ui/react" const tokens = defineTokens({ borders: { // string value subtle: { value: "1px solid red" }, // string value with reference to color token danger: { value: "1px solid {colors.red.400}" }, // composite value accent: { value: { width: "1px", color: "red", style: "solid" } }, }, }) export default createSystem({ theme: { tokens }, }) ``` Border tokens are typically used in `border`, `border-top`, `border-right`, `border-bottom`, `border-left`, `outline` properties. ### [Border Widths]() Border width tokens represent the width of a border. Its value is defined as a string. theme.ts ``` import { defineTokens } from "@chakra-ui/react" const tokens = defineTokens({ borderWidths: { thin: { value: "1px" }, thick: { value: "2px" }, medium: { value: "1.5px" }, }, }) export default createSystem({ theme: { tokens }, }) ``` ### [Shadows]() Shadow tokens represent the shadow of an element. Its value is defined as single or multiple values containing a string or a composite value. theme.ts ``` import { defineTokens } from "@chakra-ui/react" const tokens = defineTokens({ shadows: { // string value subtle: { value: "0 1px 2px 0 rgba(0, 0, 0, 0.05)" }, // composite value accent: { value: { offsetX: 0, offsetY: 4, blur: 4, spread: 0, color: "rgba(0, 0, 0, 0.1)", }, }, // multiple string values realistic: { value: [ "0 1px 2px 0 rgba(0, 0, 0, 0.05)", "0 1px 4px 0 rgba(0, 0, 0, 0.1)", ], }, }, }) export default createSystem({ theme: { tokens }, }) ``` Shadow tokens are typically used in `box-shadow` property. ### [Easings]() Easing tokens represent the easing function of an animation or transition. Its value is defined as a string or an array of values representing the cubic bezier. theme.ts ``` import { defineTokens } from "@chakra-ui/react" const tokens = defineTokens({ easings: { // string value easeIn: { value: "cubic-bezier(0.4, 0, 0.2, 1)" }, // array value easeOut: { value: [0.4, 0, 0.2, 1] }, }, }) export default createSystem({ theme: { tokens }, }) ``` Ease tokens are typically used in `transition-timing-function` property. ### [Opacity]() Opacity tokens help you set the opacity of an element. theme.ts ``` import { defineTokens } from "@chakra-ui/react" const tokens = defineTokens({ opacity: { 50: { value: 0.5 }, }, }) export default createSystem({ theme: { tokens }, }) ``` Opacity tokens are typically used in `opacity` property. ### [Z-Index]() This token type represents the depth of an element's position on the z-axis. theme.ts ``` import { defineTokens } from "@chakra-ui/react" const tokens = defineTokens({ zIndex: { modal: { value: 1000 }, }, }) export default createSystem({ theme: { tokens }, }) ``` Z-index tokens are typically used in `z-index` property. ### [Assets]() Asset tokens represent a url or svg string. Its value is defined as a string or a composite value. ``` type CompositeAsset = { type: "url" | "svg"; value: string } type Asset = string | CompositeAsset ``` theme.ts ``` import { defineTokens } from "@chakra-ui/react" const tokens = defineTokens({ tokens: { assets: { logo: { value: { type: "url", value: "/static/logo.png" }, }, checkmark: { value: { type: "svg", value: "<svg>...</svg>" }, }, }, }, }) export default createSystem({ theme: { tokens }, }) ``` Asset tokens are typically used in `background-image` property. ### [Durations]() Duration tokens represent the length of time in milliseconds an animation or animation cycle takes to complete. Its value is defined as a string. theme.ts ``` import { defineTokens } from "@chakra-ui/react" const tokens = defineTokens({ durations: { fast: { value: "100ms" }, }, }) export default createSystem({ theme: { tokens }, }) ``` Duration tokens are typically used in `transition-duration` and `animation-duration` properties. ### [Animations]() Animation tokens represent a keyframe animation. Its value is defined as a string value. theme.ts ``` import { defineTokens } from "@chakra-ui/react" const tokens = defineTokens({ animations: { spin: { value: "spin 1s linear infinite", }, }, }) export default createSystem({ theme: { tokens }, }) ``` Animation tokens are typically used in `animation` property. ### [Aspect Ratios]() Aspect ratio tokens represent the aspect ratio of an element. Its value is defined as a string. theme.ts ``` import { defineTokens } from "@chakra-ui/react" const tokens = defineTokens({ aspectRatios: { "1:1": { value: "1 / 1" }, "16:9": { value: "16 / 9" }, }, }) export default createSystem({ theme: { tokens }, }) ``` [Previous \ Overview](https://www.chakra-ui.com/docs/theming/overview) [Next \ Semantic Tokens](https://www.chakra-ui.com/docs/theming/semantic-tokens)
https://www.chakra-ui.com/docs/theming/colors
1. Design Tokens 2. Colors # Colors The list of available color tokens ## [Tokens]() Chakra UI supports the following color tokens out of the box. ## gray gray.50 #fafafa gray.100 #f4f4f5 gray.200 #e4e4e7 gray.300 #d4d4d8 gray.400 #a1a1aa gray.500 #71717a gray.600 #52525b gray.700 #3f3f46 gray.800 #27272a gray.900 #18181b gray.950 #111111 ## red red.50 #fef2f2 red.100 #fee2e2 red.200 #fecaca red.300 #fca5a5 red.400 #f87171 red.500 #ef4444 red.600 #dc2626 red.700 #991919 red.800 #511111 red.900 #300c0c red.950 #1f0808 ## pink pink.50 #fdf2f8 pink.100 #fce7f3 pink.200 #fbcfe8 pink.300 #f9a8d4 pink.400 #f472b6 pink.500 #ec4899 pink.600 #db2777 pink.700 #a41752 pink.800 #6d0e34 pink.900 #45061f pink.950 #2c0514 ## purple purple.50 #faf5ff purple.100 #f3e8ff purple.200 #e9d5ff purple.300 #d8b4fe purple.400 #c084fc purple.500 #a855f7 purple.600 #9333ea purple.700 #641ba3 purple.800 #4a1772 purple.900 #2f0553 purple.950 #1a032e ## cyan cyan.50 #ecfeff cyan.100 #cffafe cyan.200 #a5f3fc cyan.300 #67e8f9 cyan.400 #22d3ee cyan.500 #06b6d4 cyan.600 #0891b2 cyan.700 #0c5c72 cyan.800 #134152 cyan.900 #072a38 cyan.950 #051b24 ## blue blue.50 #eff6ff blue.100 #dbeafe blue.200 #bfdbfe blue.300 #a3cfff blue.400 #60a5fa blue.500 #3b82f6 blue.600 #2563eb blue.700 #173da6 blue.800 #1a3478 blue.900 #14204a blue.950 #0c142e ## teal teal.50 #f0fdfa teal.100 #ccfbf1 teal.200 #99f6e4 teal.300 #5eead4 teal.400 #2dd4bf teal.500 #14b8a6 teal.600 #0d9488 teal.700 #0c5d56 teal.800 #114240 teal.900 #032726 teal.950 #021716 ## green green.50 #f0fdf4 green.100 #dcfce7 green.200 #bbf7d0 green.300 #86efac green.400 #4ade80 green.500 #22c55e green.600 #16a34a green.700 #116932 green.800 #124a28 green.900 #042713 green.950 #03190c ## yellow yellow.50 #fefce8 yellow.100 #fef9c3 yellow.200 #fef08a yellow.300 #fde047 yellow.400 #facc15 yellow.500 #eab308 yellow.600 #ca8a04 yellow.700 #845209 yellow.800 #713f12 yellow.900 #422006 yellow.950 #281304 ## orange orange.50 #fff7ed orange.100 #ffedd5 orange.200 #fed7aa orange.300 #fdba74 orange.400 #fb923c orange.500 #f97316 orange.600 #ea580c orange.700 #92310a orange.800 #6c2710 orange.900 #3b1106 orange.950 #220a04 ## [Semantic Tokens]() Chakra UI supports these semantic tokens out of the box. info In most cases, we recommend using semantic tokens. ## background bg light: {white} dark: {black} bg.subtle light: {gray.50} dark: {gray.950} bg.muted light: {gray.100} dark: {gray.900} bg.emphasized light: {gray.200} dark: {gray.800} bg.inverted light: {black} dark: {white} bg.panel light: {white} dark: {gray.950} bg.error light: {red.50} dark: {red.950} bg.warning light: {orange.50} dark: {orange.950} bg.success light: {green.50} dark: {green.950} bg.info light: {blue.50} dark: {blue.950} ## border border light: {gray.200} dark: {gray.800} border.muted light: {gray.100} dark: {gray.900} border.subtle light: {gray.50} dark: {gray.950} border.emphasized light: {gray.300} dark: {gray.700} border.inverted light: {gray.800} dark: {gray.200} border.error light: {red.500} dark: {red.400} border.warning light: {orange.500} dark: {orange.400} border.success light: {green.500} dark: {green.400} border.info light: {blue.500} dark: {blue.400} ## text Ag fg light: {black} dark: {gray.50} Ag fg.muted light: {gray.600} dark: {gray.400} Ag fg.subtle light: {gray.400} dark: {gray.500} Ag fg.inverted light: {gray.50} dark: {black} Ag fg.error light: {red.500} dark: {red.400} Ag fg.warning light: {orange.600} dark: {orange.300} Ag fg.success light: {green.600} dark: {green.300} Ag fg.info light: {blue.600} dark: {blue.300} ## gray gray.contrast light: {white} dark: {black} gray.fg light: {gray.800} dark: {gray.200} gray.subtle light: {gray.100} dark: {gray.900} gray.muted light: {gray.200} dark: {gray.800} gray.emphasized light: {gray.300} dark: {gray.700} gray.solid light: {gray.900} dark: {white} gray.focusRing light: {gray.800} dark: {gray.200} ## red red.contrast light: white dark: white red.fg light: {red.700} dark: {red.300} red.subtle light: {red.100} dark: {red.900} red.muted light: {red.200} dark: {red.800} red.emphasized light: {red.300} dark: {red.700} red.solid light: {red.600} dark: {red.600} red.focusRing light: {red.600} dark: {red.600} ## pink pink.contrast light: white dark: white pink.fg light: {pink.700} dark: {pink.300} pink.subtle light: {pink.100} dark: {pink.900} pink.muted light: {pink.200} dark: {pink.800} pink.emphasized light: {pink.300} dark: {pink.700} pink.solid light: {pink.600} dark: {pink.600} pink.focusRing light: {pink.600} dark: {pink.600} ## purple purple.contrast light: white dark: white purple.fg light: {purple.700} dark: {purple.300} purple.subtle light: {purple.100} dark: {purple.900} purple.muted light: {purple.200} dark: {purple.800} purple.emphasized light: {purple.300} dark: {purple.700} purple.solid light: {purple.600} dark: {purple.600} purple.focusRing light: {purple.600} dark: {purple.600} ## cyan cyan.contrast light: white dark: white cyan.fg light: {cyan.700} dark: {cyan.300} cyan.subtle light: {cyan.100} dark: {cyan.900} cyan.muted light: {cyan.200} dark: {cyan.800} cyan.emphasized light: {cyan.300} dark: {cyan.700} cyan.solid light: {cyan.600} dark: {cyan.600} cyan.focusRing light: {cyan.600} dark: {cyan.600} ## blue blue.contrast light: white dark: white blue.fg light: {blue.700} dark: {blue.300} blue.subtle light: {blue.100} dark: {blue.900} blue.muted light: {blue.200} dark: {blue.800} blue.emphasized light: {blue.300} dark: {blue.700} blue.solid light: {blue.600} dark: {blue.600} blue.focusRing light: {blue.600} dark: {blue.600} ## teal teal.contrast light: white dark: white teal.fg light: {teal.700} dark: {teal.300} teal.subtle light: {teal.100} dark: {teal.900} teal.muted light: {teal.200} dark: {teal.800} teal.emphasized light: {teal.300} dark: {teal.700} teal.solid light: {teal.600} dark: {teal.600} teal.focusRing light: {teal.600} dark: {teal.600} ## green green.contrast light: white dark: white green.fg light: {green.700} dark: {green.300} green.subtle light: {green.100} dark: {green.900} green.muted light: {green.200} dark: {green.800} green.emphasized light: {green.300} dark: {green.700} green.solid light: {green.600} dark: {green.600} green.focusRing light: {green.600} dark: {green.600} ## yellow yellow.contrast light: black dark: black yellow.fg light: {yellow.800} dark: {yellow.300} yellow.subtle light: {yellow.100} dark: {yellow.900} yellow.muted light: {yellow.200} dark: {yellow.800} yellow.emphasized light: {yellow.300} dark: {yellow.700} yellow.solid light: {yellow.300} dark: {yellow.300} yellow.focusRing light: {yellow.300} dark: {yellow.300} ## orange orange.contrast light: white dark: black orange.fg light: {orange.700} dark: {orange.300} orange.subtle light: {orange.100} dark: {orange.900} orange.muted light: {orange.200} dark: {orange.800} orange.emphasized light: {orange.300} dark: {orange.700} orange.solid light: {orange.600} dark: {orange.500} orange.focusRing light: {orange.600} dark: {orange.500} [Previous \ Breakpoints](https://www.chakra-ui.com/docs/theming/breakpoints) [Next \ Cursors](https://www.chakra-ui.com/docs/theming/cursors)
https://www.chakra-ui.com/docs/theming/aspect-ratios
1. Design Tokens 2. Aspect Ratios # Aspect Ratios The list of available aspect ratios ## [Tokens]() Chakra UI supports the following aspect ratios out of the box. ## theme.tokens.aspectRatios square 1 / 1 landscape 4 / 3 portrait 3 / 4 wide 16 / 9 ultrawide 18 / 5 golden 1.618 / 1 [Previous \ Animations](https://www.chakra-ui.com/docs/theming/animations) [Next \ Breakpoints](https://www.chakra-ui.com/docs/theming/breakpoints)
https://www.chakra-ui.com/docs/theming/breakpoints
1. Design Tokens 2. Breakpoints # Breakpoints The list of available breakpoints Chakra UI supports the following breakpoints out of the box. ## theme.breakpoints sm @media screen (min-width &gt;= 480px) md @media screen (min-width &gt;= 768px) lg @media screen (min-width &gt;= 1024px) xl @media screen (min-width &gt;= 1280px) 2xl @media screen (min-width &gt;= 1536px) [Previous \ Aspect Ratios](https://www.chakra-ui.com/docs/theming/aspect-ratios) [Next \ Colors](https://www.chakra-ui.com/docs/theming/colors)
https://www.chakra-ui.com/docs/theming/animations
1. Design Tokens 2. Animations # Animations The list of available animation tokens ## [Keyframes]() Chakra UI supports the following keyframes out of the box. ## theme.keyframes spin pulse ping bounce fade-in fade-out slide-from-left-full slide-from-right-full slide-from-top-full slide-from-bottom-full slide-to-left-full slide-to-right-full slide-to-top-full slide-to-bottom-full slide-from-top slide-from-bottom slide-from-left slide-from-right slide-to-top slide-to-bottom slide-to-left slide-to-right scale-in scale-out ## [Durations]() Chakra UI supports the following durations out of the box. ## theme.tokens.durations slowest slower slow moderate fast faster fastest [Previous \ Slot Recipes](https://www.chakra-ui.com/docs/theming/slot-recipes) [Next \ Aspect Ratios](https://www.chakra-ui.com/docs/theming/aspect-ratios)
https://www.chakra-ui.com/docs/theming/spacing
1. Design Tokens 2. Spacing # Spacing The list of available spacing tokens ## [Tokens]() Chakra UI supports the following spacing tokens out of the box. ## theme.tokens.spacing Name Value Pixel 0.5 0.125rem 2px 1 0.25rem 4px 1.5 0.375rem 6px 2 0.5rem 8px 2.5 0.625rem 10px 3 0.75rem 12px 3.5 0.875rem 14px 4 1rem 16px 4.5 1.125rem 18px 5 1.25rem 20px 6 1.5rem 24px 7 1.75rem 28px 8 2rem 32px 9 2.25rem 36px 10 2.5rem 40px 11 2.75rem 44px 12 3rem 48px 14 3.5rem 56px 16 4rem 64px 20 5rem 80px 24 6rem 96px 28 7rem 112px 32 8rem 128px 36 9rem 144px 40 10rem 160px 44 11rem 176px 48 12rem 192px 52 13rem 208px 56 14rem 224px 60 15rem 240px 64 16rem 256px 72 18rem 288px 80 20rem 320px 96 24rem 384px [Previous \ Sizes](https://www.chakra-ui.com/docs/theming/sizes) [Next \ Typography](https://www.chakra-ui.com/docs/theming/typography)
https://www.chakra-ui.com/docs/theming/sizes
1. Design Tokens 2. Sizes # Sizes The list of available size tokens ## [Tokens]() Chakra UI supports the following size tokens out of the box. ## tokenSizes Name Value Pixel 0.5 0.125rem 2px 1 0.25rem 4px 1.5 0.375rem 6px 2 0.5rem 8px 2.5 0.625rem 10px 3 0.75rem 12px 3.5 0.875rem 14px 4 1rem 16px 4.5 1.125rem 18px 5 1.25rem 20px 6 1.5rem 24px 7 1.75rem 28px 8 2rem 32px 9 2.25rem 36px 10 2.5rem 40px 11 2.75rem 44px 12 3rem 48px 14 3.5rem 56px 16 4rem 64px 20 5rem 80px 24 6rem 96px 28 7rem 112px 32 8rem 128px 36 9rem 144px 40 10rem 160px 44 11rem 176px 48 12rem 192px 52 13rem 208px 56 14rem 224px 60 15rem 240px 64 16rem 256px 72 18rem 288px 80 20rem 320px 96 24rem 384px ## namedSizes Name Value max max-content min min-content fit fit-content prose 60ch full 100% dvh 100dvh svh 100svh lvh 100lvh dvw 100dvw svw 100svw lvw 100lvw vw 100vw vh 100vh ## fractionalSizes Name Value 1/2 50% 1/3 33.333333% 2/3 66.666667% 1/4 25% 3/4 75% 1/5 20% 2/5 40% 3/5 60% 4/5 80% 1/6 16.666667% 2/6 33.333333% 3/6 50% 4/6 66.666667% 5/6 83.333333% 1/12 8.333333% 2/12 16.666667% 3/12 25% 4/12 33.333333% 5/12 41.666667% 6/12 50% 7/12 58.333333% 8/12 66.666667% 9/12 75% 10/12 83.333333% 11/12 91.666667% ## breakpointSizes Name Value breakpoint-sm 480px breakpoint-md 768px breakpoint-lg 1024px breakpoint-xl 1280px breakpoint-2xl 1536px ## largeSizes Name Value 3xs 14rem 2xs 16rem xs 20rem sm 24rem md 28rem lg 32rem xl 36rem 2xl 42rem 3xl 48rem 4xl 56rem 5xl 64rem 6xl 72rem 7xl 80rem 8xl 90rem [Previous \ Shadows](https://www.chakra-ui.com/docs/theming/shadows) [Next \ Spacing](https://www.chakra-ui.com/docs/theming/spacing)
https://www.chakra-ui.com/docs/theming/text-styles
1. Compositions 2. Text Styles # Text Styles The built-in text styles in Chakra UI Chakra UI provides these text styles out of the box. textStyle: xs Chakra UI textStyle: sm Chakra UI textStyle: md Chakra UI textStyle: lg Chakra UI textStyle: xl Chakra UI textStyle: 2xl Chakra UI textStyle: 3xl Chakra UI textStyle: 4xl Chakra UI textStyle: 5xl Chakra UI textStyle: 6xl Chakra UI textStyle: 7xl Chakra UI [Previous \ Z-Index](https://www.chakra-ui.com/docs/theming/z-index) [Next \ Layer Styles](https://www.chakra-ui.com/docs/theming/layer-styles)
https://www.chakra-ui.com/docs/theming/cursors
1. Design Tokens 2. Cursors # Cursors The cursor tokens used for interactive elements. ## [Overview]() Chakra UI uses the `cursor` token to define the cursor for interactive elements. ## theme.tokens.cursor ButtonDisabled ## [Cursor Tokens]() To customize the cursor for interactive elements in Chakra, set the desired `cursor` token values. Here's a list of the available cursor tokens: - **button**: Cursors for buttons - **checkbox**: Cursors for checkbox and checkbox card - **disabled**: Cursors for disabled elements - **menuitem**: Cursors for menu item and menu option items. - **option**: Cursors for select, combobox and listbox options - **radio**: Cursors for radio and radio cards - **slider**: Cursors for slider track and thumb interaction - **switch**: Cursors for switch ## [Customizing Cursors]() Here's an example of how to change the cursor for a button, you can set the `button` token to `default`. ``` import { createSystem, defaultConfig } from "@chakra-ui/react" export const system = createSystem(defaultConfig, { theme: { tokens: { cursor: { button: { value: "pointer" }, }, }, }, }) ``` [Previous \ Colors](https://www.chakra-ui.com/docs/theming/colors) [Next \ Radii](https://www.chakra-ui.com/docs/theming/radii)
https://www.chakra-ui.com/docs/theming/typography
1. Design Tokens 2. Typography # Typography The list of available typography tokens ## [Fonts]() Here's the list of available fonts. ## theme.tokens.fonts Ag heading ``` Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol" ``` Ag body ``` Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol" ``` Ag mono ``` SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace ``` ## [Font Sizes]() Here's the list of available font sizes. ## theme.tokens.fontSizes 2xs 0.625rem Ag xs 0.75rem Ag sm 0.875rem Ag md 1rem Ag lg 1.125rem Ag xl 1.25rem Ag 2xl 1.5rem Ag 3xl 1.875rem Ag 4xl 2.25rem Ag 5xl 3rem Ag 6xl 3.75rem Ag 7xl 4.5rem Ag 8xl 6rem Ag 9xl 8rem Ag ## [Font Weights]() Here's the list of available font weights. ## theme.tokens.fontWeights thin 100 Ag extralight 200 Ag light 300 Ag normal 400 Ag medium 500 Ag semibold 600 Ag bold 700 Ag extrabold 800 Ag black 900 Ag ## [Line Heights]() Here's the list of available line heights. ## theme.tokens.lineHeights shorter / 1.25 Naruto is a Japanese manga series written and illustrated by Masashi Kishimoto. It tells the story of Naruto Uzumaki, a young ninja who seeks recognition from his peers and dreams of becoming the Hokage, the leader of his village. short / 1.375 Naruto is a Japanese manga series written and illustrated by Masashi Kishimoto. It tells the story of Naruto Uzumaki, a young ninja who seeks recognition from his peers and dreams of becoming the Hokage, the leader of his village. moderate / 1.5 Naruto is a Japanese manga series written and illustrated by Masashi Kishimoto. It tells the story of Naruto Uzumaki, a young ninja who seeks recognition from his peers and dreams of becoming the Hokage, the leader of his village. tall / 1.625 Naruto is a Japanese manga series written and illustrated by Masashi Kishimoto. It tells the story of Naruto Uzumaki, a young ninja who seeks recognition from his peers and dreams of becoming the Hokage, the leader of his village. taller / 2 Naruto is a Japanese manga series written and illustrated by Masashi Kishimoto. It tells the story of Naruto Uzumaki, a young ninja who seeks recognition from his peers and dreams of becoming the Hokage, the leader of his village. ## [Letter Spacings]() Here's the list of available letter spacing. ## theme.tokens.letterSpacings tighter / -0.05em Naruto Uzumaki tight / -0.025em Naruto Uzumaki wide / 0.025em Naruto Uzumaki wider / 0.05em Naruto Uzumaki widest / 0.1em Naruto Uzumaki [Previous \ Spacing](https://www.chakra-ui.com/docs/theming/spacing) [Next \ Z-Index](https://www.chakra-ui.com/docs/theming/z-index)
https://www.chakra-ui.com/docs/theming/shadows
1. Design Tokens 2. Shadows # Shadows The list of available shadow tokens ## [Semantic Tokens]() Chakra UI supports these semantic tokens out of the box. ## theme.semanticTokens.shadows xs sm md lg xl 2xl inner inset [Previous \ Radii](https://www.chakra-ui.com/docs/theming/radii) [Next \ Sizes](https://www.chakra-ui.com/docs/theming/sizes)
https://www.chakra-ui.com/docs/theming/radii
1. Design Tokens 2. Radii # Radii The list of available border radius tokens ## [Tokens]() Chakra UI supports the following border radius tokens out of the box. ## theme.tokens.radii none ``` 0 ``` 2xs ``` 0.0625rem ``` xs ``` 0.125rem ``` sm ``` 0.25rem ``` md ``` 0.375rem ``` lg ``` 0.5rem ``` xl ``` 0.75rem ``` 2xl ``` 1rem ``` 3xl ``` 1.5rem ``` 4xl ``` 2rem ``` full ``` 9999px ``` [Previous \ Cursors](https://www.chakra-ui.com/docs/theming/cursors) [Next \ Shadows](https://www.chakra-ui.com/docs/theming/shadows)
https://www.chakra-ui.com/docs/theming/customization/breakpoints
1. Customization 2. Breakpoints # Breakpoints Learn how to customize breakpoints in Chakra UI info Please read the [overview](https://www.chakra-ui.com/docs/theming/customization/overview) first to learn how to properly customize the styling engine, and get type safety. ## [Example]() Here's an example of how to customize breakpoints in Chakra UI. theme.ts ``` import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react" const config = defineConfig({ theme: { breakpoints: { tablet: "992px", desktop: "1200px", wide: "1400px", }, }, }) export default createSystem(defaultConfig, config) ``` ## [Usage]() When using responsive properties, reference the new breakpoints. App.tsx ``` <Box fontSize={{ base: "16px", tablet: "18px", desktop: "20px" }}>Hello</Box> ``` [Previous \ Animations](https://www.chakra-ui.com/docs/theming/customization/animations) [Next \ Colors](https://www.chakra-ui.com/docs/theming/customization/colors)
https://www.chakra-ui.com/docs/theming/customization/animations
1. Customization 2. Animations # Animations Learn how to customize animations and keyframes in Chakra UI info Please read the [overview](https://www.chakra-ui.com/docs/theming/customization/overview) first to learn how to properly customize the styling engine, and get type safety. ## [Keyframes]() Keyframes are used to define the animation sequence. Here's how to define custom keyframes: theme.ts ``` import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react" const config = defineConfig({ theme: { keyframes: { shakeX: { "0%, 100%": { transform: "translateX(-100%)" }, "50%": { transform: "translateX(100%)" }, }, }, }, }) export const system = createSystem(defaultConfig, config) ``` ## [Animation Tokens]() After defining keyframes, you can create animation tokens that reference them. Animation tokens can include the keyframe name, duration, timing function, and other animation properties. theme.ts ``` import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react" const config = defineConfig({ theme: { keyframes: { // ... keyframes from above }, tokens: { animations: { shakeX: { value: "shakeX 1s ease-in-out infinite" }, }, }, }, }) export const system = createSystem(defaultConfig, config) ``` ## [Usage]() You can use the animation token directly in your component style props. ``` <Box animation="shakeX" /> ``` or as individual animation properties ``` <Box animationName="shakeX" animationDuration="1s" animationTimingFunction="ease-in-out" animationIterationCount="infinite" /> ``` [Previous \ Overview](https://www.chakra-ui.com/docs/theming/customization/overview) [Next \ Breakpoints](https://www.chakra-ui.com/docs/theming/customization/breakpoints)
https://www.chakra-ui.com/docs/theming/z-index
1. Design Tokens 2. Z-Index # Z-Index The list of available z-index tokens ## [Tokens]() Chakra UI supports the following z-index tokens out of the box. ## theme.tokens.zIndex Name Value hide -1 base 0 docked 10 dropdown 1000 sticky 1100 banner 1200 overlay 1300 modal 1400 popover 1500 skipNav 1600 toast 1700 tooltip 1800 max 2147483647 [Previous \ Typography](https://www.chakra-ui.com/docs/theming/typography) [Next \ Text Styles](https://www.chakra-ui.com/docs/theming/text-styles)
https://www.chakra-ui.com/docs/theming/layer-styles
1. Compositions 2. Layer Styles # Slot Recipes The built-in layer styles in Chakra UI Chakra UI provides these text styles out of the box. layerStyle: fill.* fill.muted fill.subtle fill.surface fill.solid layerStyle: outline.* outline.subtle outline.solid layerStyle: indicator.* indicator.top indicator.bottom indicator.start indicator.end [Previous \ Text Styles](https://www.chakra-ui.com/docs/theming/text-styles) [Next \ Overview](https://www.chakra-ui.com/docs/theming/customization/overview)
https://www.chakra-ui.com/docs/theming/customization/overview
1. Customization 2. Overview # Customization Learn how to customize the Chakra UI theme ## [Overview]() Chakra UI uses a system of configs to define the default styling system. - `defaultBaseConfig`: contains the conditions and style properties. - `defaultConfig`: everything from `defaultBaseConfig` plus the built-in tokens and recipes. The `defaultSystem` exported from Chakra UI uses the `defaultConfig` by default. When customizing the theme, it's important to decide if you want to merge your config with `defaultConfig` or start from scratch with `defaultBaseConfig`. ## [Customization]() These are the key functions needed to customize the Chakra UI theme. - `defineConfig`: used to define the system config - `mergeConfigs`: used to merge multiple system configs - `createSystem`: used to create a styling engine from the config theme.ts ``` import { createSystem, defaultBaseConfig, defineConfig } from "@chakra-ui/react" const customConfig = defineConfig({ theme: { colors: { brand: { 500: "tomato", }, }, }, }) export const system = createSystem(defaultBaseConfig, customConfig) ``` Next, update the `ChakraProvider` to use the custom system. provider.tsx ``` import { ChakraProvider } from "@chakra-ui/react" import { ThemeProvider } from "next-themes" import { system } from "./theme" export function Provider(props: { children: React.ReactNode }) { return ( <ChakraProvider value={system}> <ThemeProvider attribute="class" disableTransitionOnChange> {props.children} </ThemeProvider> </ChakraProvider> ) } ``` ## [Complete Customization]() In most cases, we recommend starting with the default configuration and only specify the things you want to customize. However, if you prefer to start from scratch, scaffold the default tokens and recipes using the CLI. ``` npx @chakra-ui/cli eject --outdir ./theme ``` This will generate a file that includes all the tokens and recipes in Chakra. ## [TypeScript]() After customizing the default config, you may need to update the types. ``` npx @chakra-ui/cli typegen ./theme.ts ``` [Previous \ Layer Styles](https://www.chakra-ui.com/docs/theming/layer-styles) [Next \ Animations](https://www.chakra-ui.com/docs/theming/customization/animations)
https://www.chakra-ui.com/docs/theming/customization/colors
1. Customization 2. Colors # Colors Learn how to customize colors in Chakra UI info Please read the [overview](https://www.chakra-ui.com/docs/theming/customization/overview) first to learn how to properly customize the styling engine, and get type safety. ## [Tokens]() To create new colors, we recommend providing `50` - `950` color values. Here's an example of how to customize colors in Chakra UI. theme.ts ``` import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react" const customConfig = defineConfig({ theme: { tokens: { colors: { brand: { 50: { value: "#e6f2ff" }, 100: { value: "#e6f2ff" }, 200: { value: "#bfdeff" }, 300: { value: "#99caff" }, // ... 950: { value: "#001a33" }, }, }, }, }, }) export const system = createSystem(defaultConfig, customConfig) ``` To use the `brand` color, you can set the value of any color related properties, like `bg`, `borderColor`, `color`, etc. to the `brand` token. ``` <Box bg="brand.100" /> ``` ## [Semantic Tokens]() ### [Color Palette]() For new colors defined in the theme, we recommend creating these matching semantic tokens to ensure consistency. - `solid`: The bold fill color of the color. - `contrast`: The text color that goes on solid color. - `fg`: The foreground color used for text, icons, etc. - `muted`: The muted color of the color. - `subtle`: The subtle color of the color. - `emphasized`: The emphasized version of the subtle color. - `focusRing`: The focus ring color when interactive element is focused. note This is required if you intend to use the color in `colorPalette` property. theme.ts ``` const customConfig = defineConfig({ theme: { tokens: { colors: { brand: { // ... }, }, }, semanticTokens: { colors: { brand: { solid: { value: "{colors.brand.500}" }, contrast: { value: "{colors.brand.100}" }, fg: { value: "{colors.brand.700}" }, muted: { value: "{colors.brand.100}" }, subtle: { value: "{colors.brand.200}" }, emphasized: { value: "{colors.brand.300}" }, focusRing: { value: "{colors.brand.500}" }, }, }, }, }, }) ``` To use the color palette in components, you can use the `colorPalette` property. ``` <Button colorPalette="brand">Click me</Button> ``` Alternative, you can also use the semantic token directly. ``` <Box color="brand.contrast" bg="brand.solid"> Hello world </Box> ``` ### [Custom Tokens]() Here's an example of how to create custom semantic tokens. theme.ts ``` import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react" const customConfig = defineConfig({ theme: { semanticTokens: { colors: { "checkbox-border": { value: { _light: "gray.200", _dark: "gray.800" }, }, }, }, }, }) export const system = createSystem(defaultConfig, customConfig) ``` Then, you can apply the `checkbox-border` token to any component. ``` <Square size="4" borderColor="checkbox-border"> <LuCheck /> </Square> ``` [Previous \ Breakpoints](https://www.chakra-ui.com/docs/theming/customization/breakpoints) [Next \ Conditions](https://www.chakra-ui.com/docs/theming/customization/conditions)
https://www.chakra-ui.com/docs/theming/customization/css-variables
1. Customization 2. CSS Variables # CSS Variables Learn how to customize CSS variables in Chakra UI info Please read the [overview](https://www.chakra-ui.com/docs/theming/customization/overview) first to learn how to properly customize the styling engine, and get type safety. ## [Variable Root]() Here's an example of how to customize the selector that token CSS variables are applied to. theme.ts ``` import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react" const customConfig = defineConfig({ cssVarsRoot: ":where(html)", }) export const system = createSystem(defaultConfig, customConfig) ``` The emitted CSS variables will now be applied to the `html` element. ``` :where(html) { --chakra-colors-gray-100: #e6f2ff; --chakra-colors-gray-200: #bfdeff; --chakra-colors-gray-300: #99caff; } ``` ## [Variable Prefix]() Here's an example of how to customize the prefix of the emitted CSS variables. theme.ts ``` import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react" const customConfig = defineConfig({ cssVarsPrefix: "sui", }) export const system = createSystem(defaultConfig, customConfig) ``` The emitted CSS variables will now use the `sui` prefix. ``` :where(html) { --sui-colors-gray-100: #e6f2ff; --sui-colors-gray-200: #bfdeff; --sui-colors-gray-300: #99caff; } ``` [Previous \ Conditions](https://www.chakra-ui.com/docs/theming/customization/conditions) [Next \ Global CSS](https://www.chakra-ui.com/docs/theming/customization/global-css)
https://www.chakra-ui.com/docs/theming/customization/conditions
1. Customization 2. Conditions # Conditions Learn how to customize conditions in Chakra UI info Please read the [overview](https://www.chakra-ui.com/docs/theming/customization/overview) first to learn how to properly customize the styling engine, and get type safety. ## [Example]() Here's an example of how to customize conditions in Chakra UI. theme.ts ``` import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react" const customConfig = defineConfig({ conditions: { off: "&:is([data-state=off])", on: "&:is([data-state=on])", }, }) export const system = createSystem(defaultConfig, customConfig) ``` ## [Usage]() Use `_off` and `_on` conditions to style elements based on the `data-state` attribute. app.tsx ``` import { Box } from "@chakra-ui/react" <Box data-state="off" _off={{ bg: "red.500" }} /> <Box data-state="on" _on={{ bg: "green.500" }} /> ``` [Previous \ Colors](https://www.chakra-ui.com/docs/theming/customization/colors) [Next \ CSS Variables](https://www.chakra-ui.com/docs/theming/customization/css-variables)
https://www.chakra-ui.com/docs/theming/customization/global-css
1. Customization 2. Global CSS # Global CSS Learn how to customize global CSS in Chakra UI info Please read the [overview](https://www.chakra-ui.com/docs/theming/customization/overview) first to learn how to properly customize the styling engine, and get type safety. ## [Example]() Here's an example of how to customize the global CSS in Chakra UI. theme.ts ``` import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react" const customConfig = defineConfig({ globalCss: { "*::placeholder": { opacity: 1, color: "fg.subtle", }, "*::selection": { bg: "green.200", }, }, }) export const system = createSystem(defaultConfig, customConfig) ``` After customizing the global CSS, make sure to update your provider component to use the new system. components/ui/provider.tsx ``` "use client" import { system } from "@/components/theme" import { ColorModeProvider, type ColorModeProviderProps, } from "@/components/ui/color-mode" import { ChakraProvider } from "@chakra-ui/react" export function Provider(props: ColorModeProviderProps) { return ( <ChakraProvider value={system}> <ColorModeProvider {...props} /> </ChakraProvider> ) } ``` [Previous \ CSS Variables](https://www.chakra-ui.com/docs/theming/customization/css-variables) [Next \ Recipes](https://www.chakra-ui.com/docs/theming/customization/recipes)
https://www.chakra-ui.com/docs/theming/customization/recipes
1. Customization 2. Recipes # Recipes Learn how to customize recipes and slot recipes in Chakra UI info Please read the [overview](https://www.chakra-ui.com/docs/theming/customization/overview) first to learn how to properly customize the styling engine, and get type safety. ## [Recipes]() ### [Extending variants]() Use the `defineRecipe` function to define a recipe override. Here's an example of extending the `Button` to add a new `xl` size theme.ts ``` const buttonRecipe = defineRecipe({ variants: { size: { xl: { fontSize: "lg", px: 6, py: 3, }, }, }, }) const customConfig = defineConfig({ theme: { recipes: { button: buttonRecipe, }, }, }) export const system = createSystem(defaultConfig, customConfig) ``` Then you can use the new size variant in your components. ``` <Button size="xl">Click me</Button> ``` ### [Adding new variant]() Use the `defineRecipe` function to define a new recipe variant. Here's an example of defining a boolean variant called `raised`. theme.ts ``` const buttonRecipe = defineRecipe({ variants: { raised: { true: { boxShadow: "md", }, }, }, }) const customConfig = defineConfig({ theme: { recipes: { button: buttonRecipe, }, }, }) export const system = createSystem(defaultConfig, customConfig) ``` Then you can use the new variant in your components. ``` <Button raised>Click me</Button> ``` ### [Custom recipe]() Use the `defineRecipe` function to define a custom recipe all together. Here's an example of defining a custom recipe called `Title` theme.ts ``` const titleRecipe = defineRecipe({ baseStyle: { fontWeight: "bold", letterSpacing: "tight", }, variants: { size: { md: { fontSize: "xl" }, lg: { fontSize: "2xl" }, }, }, }) const customConfig = defineConfig({ theme: { recipes: { title: titleRecipe, }, }, }) export const system = createSystem(defaultConfig, customConfig) ``` Then, use the new recipe to create a components ``` const Title = (props) => { const recipe = useRecipe({ key: "title" }) const styles = recipe({ size: "lg" }) return <Box as="h1" css={styles} {...props} /> } ``` ## [Slot Recipes]() To effectively override an existing slot recipe, we recommend connecting to its anatomy. Slot recipes are added to the `theme.slotRecipes` object. ### [Extending variants]() Here's an example of how to extend the `Alert` slot recipe to create an `xl` size. theme.ts ``` import { alertAnatomy } from "@chakra-ui/react/anatomy" const alertSlotRecipe = defineSlotRecipe({ slots: alertAnatomy.keys(), variants: { size: { xl: { root: { fontSize: "lg", px: 6, py: 3, }, }, }, }, }) const customConfig = defineConfig({ theme: { slotRecipes: { alert: alertSlotRecipe, }, }, }) export const system = createSystem(defaultConfig, customConfig) ``` Then you can use the new size variant in your components. ``` <Alert size="xl" title="..." /> ``` ### [Adding new variant]() Here's an example of how to extend the `Alert` slot recipe to add a new variant called `shape`. theme.ts ``` import { alertAnatomy } from "@chakra-ui/react/anatomy" const alertSlotRecipe = defineSlotRecipe({ slots: alertAnatomy.keys(), variants: { shape: { rounded: { root: { borderRadius: "full" }, }, }, }, }) const customConfig = defineConfig({ theme: { slotRecipes: { alert: alertSlotRecipe, }, }, }) export const system = createSystem(defaultConfig, customConfig) ``` Then you can use the new variant in your components. ``` <Alert shape="rounded" title="..." /> ``` ### [Custom recipe]() Here's an example of how to define a custom slot recipe called `Navbar`. theme.ts ``` const navbarSlotRecipe = defineSlotRecipe({ slots: ["root", "badge", "icon"], base: { root: { bg: "blue.500", color: "white", px: 4, py: 2, }, badge: { borderRadius: "full", px: 2, py: 1, }, }, }) const customConfig = defineConfig({ theme: { slotRecipes: { navbar: navbarSlotRecipe, }, }, }) export const system = createSystem(defaultConfig, customConfig) ``` Then you can use the new recipe to create a components ``` const Navbar = (props) => { const recipe = useSlotRecipe({ key: "navbar" }) const styles = recipe() return ( <Box css={styles.root}> {props.children} <Box css={styles.badge} /> <Box css={styles.icon} /> </Box> ) } ``` [Previous \ Global CSS](https://www.chakra-ui.com/docs/theming/customization/global-css) [Next \ Sizes](https://www.chakra-ui.com/docs/theming/customization/sizes)
https://www.chakra-ui.com/docs/theming/customization/sizes
1. Customization 2. Sizes # Sizes Learn how to customize sizes in Chakra UI info Please read the [overview](https://www.chakra-ui.com/docs/theming/customization/overview) first to learn how to properly customize the styling engine, and get type safety. ## [Example]() Here's an example of how to customize sizes in Chakra UI. theme.ts ``` import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react" const customConfig = defineConfig({ theme: { tokens: { sizes: { "1/7": { value: "14.285%" }, "2/7": { value: "28.571%" }, "3/7": { value: "42.857%" }, }, }, }, }) export const system = createSystem(defaultConfig, customConfig) ``` ## [Usage]() Set the value of any size related properties, like `width`, `height`, `minWidth`, `minHeight`, `maxWidth`, `maxHeight`, etc. to the `sizes` token. ``` <Box width="1/7" height="2/7" /> ``` [Previous \ Recipes](https://www.chakra-ui.com/docs/theming/customization/recipes) [Next \ Spacing](https://www.chakra-ui.com/docs/theming/customization/spacing)
https://www.chakra-ui.com/docs/theming/customization/spacing
1. Customization 2. Spacing # Spacing Learn how to customize spacing in Chakra UI info Please read the [overview](https://www.chakra-ui.com/docs/theming/customization/overview) first to learn how to properly customize the styling engine, and get type safety. ## [Example]() Here's an example of how to customize spacing in Chakra UI. theme.ts ``` import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react" const customConfig = defineConfig({ theme: { tokens: { spacing: { "128": { value: "32rem" }, "144": { value: "36rem" }, }, }, }, }) export const system = createSystem(defaultConfig, customConfig) ``` ## [Usage]() Here's how to use the custom spacing in Chakra UI. ``` <Box margin="128" /> ``` [Previous \ Sizes](https://www.chakra-ui.com/docs/theming/customization/sizes) [Next \ Playground](https://www.chakra-ui.com/playground)
https://www.chakra-ui.com/docs/styling/dark-mode
1. Concepts 2. Dark Mode # Dark Mode Learn how to use dark mode in Chakra UI applications Chakra relies on the `next-themes` library to provide dark mode support. During the installation process, the snippets required to get started are added to your project via the CLI. ## [Setup]() If you haven't already, you can add the `next-themes` library to your project via the CLI. ``` npx @chakra-ui/cli snippet add color-mode ``` The generated snippets consists of the following: - `ColorModeProvider`: composes the `next-themes` provider component - `useColorMode`: provides the current color mode and a function to toggle the color mode - `useColorModeValue`: returns the correct value based on the current color mode - `ColorModeButton`: can be used to toggle the color mode ## [Usage]() Wrap your app with the `ColorModeProvider` and use the `useColorMode` hook to access and toggle the color mode. ``` import { ColorModeProvider } from "@/components/ui/color-mode" import { ChakraProvider, defaultSystem } from "@chakra-ui/react" export default function Layout({ children }: { children: React.ReactNode }) { return ( <ChakraProvider theme={defaultSystem}> <ColorModeProvider>{children}</ColorModeProvider> </ChakraProvider> ) } ``` ### [Adding the dark mode toggle]() Use the `ColorModeButton` component to toggle the color mode. ``` import { ColorModeButton } from "@/components/ui/color-mode" export default function Page({ children }: { children: React.ReactNode }) { return ( <> <ColorModeButton /> {children} </> ) } ``` ### [Styling dark mode]() Use the `_dark` condition to style components for dark mode. ``` <Box bg={{ base: "white", _dark: "black" }}> <Text>Hello</Text> </Box> ``` or ``` <Box bg="white" _dark={{ bg: "black" }}> <Text>Hello</Text> </Box> ``` ## [Using semantic tokens]() To reduce the amount of code you need to write, use semantic tokens to style components for dark mode. This ensures the light and dark mode styles are applied automatically and consistently. Chakra provides a set of semantic tokens that you can use to style components for dark mode. Learn more about [semantic tokens](https://www.chakra-ui.com/docs/theming/semantic-tokens). ``` <Box bg="bg.subtle"> <Text>Hello</Text> </Box> ``` ## [Forcing dark mode]() ### [Element specific dark mode]() To force dark mode, set the `dark` className on any parent element, or the root element of your application. ``` <Box bg="black" className="dark"> <Box bg="bg.subtle"> <Text>Hello</Text> </Box> </Box> ``` ### [Page specific dark mode]() Use the `ColorModeProvider` component to set the dark mode for a page. ``` <ColorModeProvider forcedTheme="dark"> <Box bg="black" className="dark"> <Box bg="bg.subtle"> <Text>Hello</Text> </Box> </Box> </ColorModeProvider> ``` Follow this `next-themes` guide to learn more about [forcing color mode](https://github.com/pacocoursey/next-themes). [Previous \ CSS Variables](https://www.chakra-ui.com/docs/styling/css-variables) [Next \ Color Opacity Modifier](https://www.chakra-ui.com/docs/styling/color-opacity-modifier)
https://www.chakra-ui.com/docs/styling/style-props/typography
1. Style Props 2. Typography # Typography JSX style props for styling text ## [Font Family]() Use the `fontFamily` prop to set the font family of a text element. ``` <Text fontFamily="mono">Hello World</Text> ``` PropCSS PropertyToken Category`fontFamily``font-family``fonts` ## [Font Size]() Use the `fontSize` prop to set the font size of a text element. ``` // hardcoded values <Text fontSize="12px">Hello World</Text> <Text fontSize="10rem">Hello World</Text> // token values <Text fontSize="xs">Hello World</Text> <Text fontSize="4xl">Hello World</Text> <Text fontSize="5xl">Hello World</Text> ``` PropCSS PropertyToken Category`fontSize``font-size``fonts` ## [Text Styles]() Use the `textStyle` prop to apply both a font size, line height, and letter spacing composition at once. ``` <Text textStyle="xs">Hello World</Text> <Text textStyle="sm">Hello World</Text> <Text textStyle="md">Hello World</Text> <Text textStyle="lg">Hello World</Text> <Text textStyle="xl">Hello World</Text> <Text textStyle="2xl">Hello World</Text> <Text textStyle="3xl">Hello World</Text> <Text textStyle="4xl">Hello World</Text> <Text textStyle="5xl">Hello World</Text> ``` PropConfig`textStyle``theme.textStyles` ## [Font Style]() Use the `fontStyle` prop to set the font style of a text element. ``` <Text fontStyle="italic">Hello World</Text> ``` PropCSS PropertyToken Category`fontStyle``font-style`none ## [Font Weight]() Use the `fontWeight` prop to set the font weight of a text element. ``` // hardcoded values <Text fontWeight="600">Hello World</Text> // token values <Text fontWeight="semibold">Hello World</Text> ``` PropCSS PropertyToken Category`fontWeight``font-weight``fontWeights` ## [Font Variant Numeric]() Use the `fontVariantNumeric` prop to set the font variant numeric of a text element. ``` <Text fontVariantNumeric="lining-nums">Hello World</Text> ``` PropCSS PropertyToken Category`fontVariantNumeric``font-variant-numeric`none ## [Letter Spacing]() Use the `letterSpacing` prop to set the letter spacing of a text element. ``` // hardcoded values <Text letterSpacing="0.1rem">Hello World</Text> // token values <Text letterSpacing="tight">Hello World</Text> <Text letterSpacing="wide">Hello World</Text> <Text letterSpacing="wider">Hello World</Text> <Text letterSpacing="widest">Hello World</Text> ``` PropCSS PropertyToken Category`letterSpacing``letter-spacing``letterSpacings` ## [Truncation]() Use the `truncate` prop to truncate text. ``` <Text truncate>Lorem ipsum dolor sit amet...</Text> ``` PropCSS PropertyToken Category`truncate``text-overflow`none ## [Line Clamp]() Use the `lineClamp` prop to truncate multi-line text. Set `lineClamp` to `none` to disable truncation. ``` <Text lineClamp="2">Lorem ipsum dolor sit amet...</Text> // revert truncation <Text lineClamp="none">Lorem ipsum dolor sit amet...</Text> ``` PropCSS PropertyToken Category`lineClamp``webkit-line-clamp`none ## [Line Height]() Use the `lineHeight` prop to set the line height of a text element. ``` // hardcoded values <Text lineHeight="1.5">Hello World</Text> // token values <Text lineHeight="tall">Hello World</Text> ``` PropCSS PropertyToken Category`lineHeight``line-height``lineHeights` ## [Text Align]() Use the `textAlign` prop to set the text alignment of a text element. ``` <Text textAlign="left">Hello World</Text> <Text textAlign="center">Hello World</Text> <Text textAlign="right">Hello World</Text> <Text textAlign="justify">Hello World</Text> ``` PropCSS PropertyToken Category`textAlign``text-align`none ## [Text Color]() Use the `color` prop to set the color of a text element. ``` <Text color="red">Hello World</Text> ``` PropCSS PropertyToken Category`color``color``colors` ## [Text Decoration]() Use the `textDecoration` or `textDecor` prop to set the text decoration of a text element. ``` <Text textDecoration="underline">Hello World</Text> ``` PropCSS PropertyToken Category`textDecor`, `textDecoration``text-decoration`none ## [Text Decoration Color]() Use the `textDecorationColor` prop to set the text decoration color of a text element. ``` <Text textDecoration="underline" textDecorationColor="red"> Hello World </Text> ``` PropCSS PropertyToken Category`textDecorationColor``text-decoration-color``colors` ## [Text Decoration Style]() Use the `textDecorationStyle` prop to set the text decoration style of a text element. ``` <Text textDecoration="underline" textDecorationStyle="dashed"> Hello World </Text> ``` PropCSS PropertyToken Category`textDecorationStyle``text-decoration-style`none ## [Text Decoration Thickness]() Use the `textDecorationThickness` prop to set the text decoration thickness of a text element. ``` <Text textDecoration="underline" textDecorationThickness="1px"> Hello World </Text> ``` PropCSS PropertyToken Category`textDecorationThickness``text-decoration-thickness`none ## [Text Underline Offset]() Use the `textUnderlineOffset` prop to set the text underline offset of a text element. ``` <Text textDecoration="underline" textUnderlineOffset="1px"> Hello World </Text> ``` PropCSS PropertyToken Category`textUnderlineOffset``text-underline-offset`none ## [Text Transform]() Use the `textTransform` prop to set the text transform of a text element. ``` <Text textTransform="uppercase">Hello World</Text> ``` PropCSS PropertyToken Category`textTransform``text-transform`none ## [Text Overflow]() Use the `textOverflow` prop to set the text overflow of a text element. ``` <Text textOverflow="ellipsis">Hello World</Text> ``` PropCSS PropertyToken Category`textOverflow``text-overflow`none ## [Text Shadow]() Use the `textShadow` prop to set the text shadow of a text element. ``` <Text textShadow="0 0 1px red">Hello World</Text> ``` PropCSS PropertyToken Category`textShadow``text-shadow``shadows` ## [Text Indent]() Use the `textIndent` prop to set the text indent of a text element. ``` // hardcoded values <Text textIndent="1rem">Hello World</Text> // token values <Text textIndent="3">Hello World</Text> ``` PropCSS PropertyToken Category`textIndent``text-indent``spacing` ## [Vertical Align]() Use the `verticalAlign` prop to set the vertical alignment of a text element. ``` <Text verticalAlign="top">Hello World</Text> ``` PropCSS PropertyToken Category`verticalAlign``vertical-align`none ## [White Space]() Use the `whiteSpace` prop to set the white space of a text element. ``` <Text whiteSpace="nowrap">Hello World</Text> ``` PropCSS PropertyToken Category`whiteSpace``white-space`none ## [Word Break]() Use the `wordBreak` prop to set whether line breaks appear wherever the text would otherwise overflow its content box. ``` <Text wordBreak="break-all">Hello World</Text> ``` PropCSS PropertyToken Category`wordBreak``word-break`none ## [Hyphens]() Use the `hyphens` prop to set whether hyphens are used in the text. ``` <Text hyphens="auto">Hello World</Text> ``` PropCSS PropertyToken Category`hyphens``hyphens`none [Previous \ Transitions](https://www.chakra-ui.com/docs/styling/style-props/transitions) [Next \ Overview](https://www.chakra-ui.com/docs/theming/overview)
https://www.chakra-ui.com/docs/styling/chakra-factory
1. Concepts 2. Chakra Factory # Chakra Factory Use the chakra factory to create supercharged components ## [Overview]() Chakra factory serves as a way to create supercharged JSX component from any HTML element to enable them receive JSX style props. ``` import { chakra } from "@chakra-ui/react" ``` The chakra factory can be used in two ways: as a JSX element or as a factory function. ## [JSX Element]() Style props are CSS properties that you can pass as props to your components. With the JSX factory, you can use `chakra.<element>` syntax to create JSX elements that support style props. ``` import { chakra } from "@chakra-ui/react" const Button = ({ children }) => ( <chakra.button bg="blue.500" color="white" py="2" px="4" rounded="md"> {children} </chakra.button> ) ``` ## [Factory function]() Use the `chakra` function to convert native elements or custom components. The key requirement is that the component **must** accept `className` as props. ``` const Link = chakra("a") function Example() { return <Link bg="red.200" href="https://chakra-ui.com" /> } ``` Another example with a custom component. ``` import * as RadixScrollArea from "@radix-ui/react-scroll-area" const ScrollArea = chakra(RadixScrollArea.Root) function Example() { return ( <ScrollArea> <RadixScrollArea.Viewport> <div>Hello</div> </RadixScrollArea.Viewport> </ScrollArea> ) } ``` ### [Attaching styles]() Use the `chakra` function to attach styles or recipes to components. ``` const Link = chakra("a", { base: { bg: "papayawhip", color: "red.500", }, }) // usage: <Link href="https://chakra-ui.com" /> ``` ### [Attaching recipes]() Here's an example of attaching a recipe to the component. ``` const Card = chakra("div", { base: { shadow: "lg", rounded: "lg", bg: "white", }, variants: { variant: { outline: { border: "1px solid", borderColor: "red.500", }, solid: { bg: "red.500", color: "white", }, }, }, }) // usage: <Card variant="outline" /> ``` ### [Forwarding props]() By default, the `chakra` factory only filters chakra related style props from getting to the DOM. For more fine-grained control of how props are forwarded, pass the `shouldForwardProp` option. Here's an example that forwards all props that doesn't start with `$` ``` const Component = chakra("div", { shouldForwardProp(prop) { return !prop.startsWith("$") }, }) ``` To create custom forward props logic, combine the [@emotion/is-prop-valid](https://github.com/emotion-js/emotion/tree/master/packages/is-prop-valid) package and the `isValidProperty` from Chakra UI. ``` import { chakra, defaultSystem } from "@chakra-ui/react" import shouldForwardProp from "@emotion/is-prop-valid" const { isValidProperty } = defaultSystem const Component = chakra("div", { shouldForwardProp(prop, variantKeys) { const chakraSfp = !variantKeys?.includes(prop) && !isValidProperty(prop) return shouldForwardProp(prop) && chakraSfp }, }) ``` ## [Default Props]() Use the `defaultProps` option to pass default props to the component. ``` const Button = chakra( "button", { base: { bg: "blue.500", color: "white", }, }, { defaultProps: { type: "button" } }, ) ``` ## [Polymorphism]() Every component created with the chakra factory can accept the `as` and `asChild` props to change the underlying DOM element. ``` <Button as="a" href="https://chakra-ui.com"> Chakra UI </Button> ``` or ``` <Button asChild> <a href="https://chakra-ui.com">Chakra UI</a> </Button> ``` Learn more about composition in Chakra UI [here](https://www.chakra-ui.com/docs/components/overview/composition) [Previous \ Overview](https://www.chakra-ui.com/docs/styling/overview) [Next \ Responsive Design](https://www.chakra-ui.com/docs/styling/responsive-design)
https://www.chakra-ui.com/docs/styling/responsive-design
1. Concepts 2. Responsive Design # Responsive Design Learn how to create responsive designs using Chakra UI's built-in responsive style props ## [Overview]() Responsive design is a fundamental aspect of modern web development, allowing websites and applications to adapt seamlessly to different screen sizes and devices. info Chakra uses a mobile-first breakpoint system and leverages min-width media queries `@media(min-width)` when you write responsive styles. Chakra provides five breakpoints by default: ``` const breakpoints = { base: "0em", // 0px sm: "30em", // ~480px md: "48em", // ~768px lg: "62em", // ~992px xl: "80em", // ~1280px "2xl": "96em", // ~1536px } ``` ## [Object syntax]() Here's an example of how to change the font weight of a text on large screens ``` <Text fontWeight="medium" lg={{ fontWeight: "bold" }}> Text </Text> ``` or use the prop based modifier ``` <Text fontWeight={{ base: "medium", lg: "bold" }}>Text</Text> ``` ## [Array syntax]() Chakra also accepts arrays as values for responsive styles. Pass the corresponding value for each breakpoint in the array. Using our previous code as an example: ``` <Text fontWeight={["medium", undefined, undefined, "bold"]}>Text</Text> ``` Notice the use of `undefined` for the breakpoints to skip the `md` and `lg` breakpoints. ## [Breakpoint targeting]() ### [Breakpoint range]() Chakra provides a way to target a range of breakpoints using the `To` notation. To apply styles between the `md` and `xl` breakpoints, use the `mdToXl` property: ``` <Text fontWeight={{ mdToXl: "bold" }}>Text</Text> ``` This text will only be bold from `md` to `xl` breakpoints. ### [Only breakpoint]() To target a single breakpoint, use the `Only` notation. Here's an example of how to apply styles only in the `lg` breakpoint, using the `lgOnly` property: ``` <Text fontWeight={{ lgOnly: "bold" }}>Text</Text> ``` ## [Hiding elements at breakpoint]() Chakra provides the `hideFrom` and `hideBelow` utilities to hide elements at specific breakpoints. To hide an element from the `md` breakpoint, use the `hideFrom` utility: ``` <Stack hideFrom="md"> <Text>This text will be hidden from the `md` breakpoint</Text> </Stack> ``` To hide an element below the `md` breakpoint, use the `hideBelow` utility: ``` <Stack hideBelow="md"> <Text>This text will be hidden below the `md` breakpoint</Text> </Stack> ``` ## [Customizing Breakpoints]() To learn how to customize breakpoints, please refer to the [customizing breakpoints](https://www.chakra-ui.com/docs/theming/customization/breakpoints) section. [Previous \ Chakra Factory](https://www.chakra-ui.com/docs/styling/chakra-factory) [Next \ CSS Variables](https://www.chakra-ui.com/docs/styling/css-variables)
https://www.chakra-ui.com/docs/styling/css-variables
1. Concepts 2. CSS Variables # CSS Variables Using token-aware CSS variables in Chakra UI ## [Overview]() CSS variables have become the defacto way to create shared values on the web. It's very useful to avoid prop interpolations, classname regeneration, and reduce runtime evaluation of token values. ## [Examples]() ### [Basic]() Use the `css` prop to create css variables ``` <Box css={{ "--font-size": "18px" }}> <h3 style={{ fontSize: "calc(var(--font-size) * 2)" }}>Hello</h3> <p style={{ fontSize: "var(--font-size)" }}>Hello</p> </Box> ``` ### [Access tokens]() Use the full token path to access tokens ``` <Box css={{ "--color": "colors.red.500" }}> <p style={{ color: "var(--color)" }}>Hello</p> </Box> ``` Here's an example of how to access size tokens ``` <Box css={{ "--size": "sizes.10" }}> <p style={{ width: "var(--size)", height: "var(--size)" }}>Hello</p> </Box> ``` ### [Responsive Styles]() Use the responsive syntax to make css variables responsive ``` <Box css={{ "--font-size": { base: "18px", lg: "24px" } }}> <h3 style={{ fontSize: "calc(var(--font-size) * 2)" }}>Hello</h3> <p style={{ fontSize: "var(--font-size)" }}>Hello</p> </Box> ``` ### [Color Opacity Modifier]() When accessing color tokens, you can use the opacity modifier to access the color with an opacity. The requirement is to use the `{}` syntax. ``` <Box css={{ "--color": "{colors.red.500/40}" }}> <p style={{ color: "var(--color)" }}>Hello</p> </Box> ``` ### [Virtual Color]() Variables can point to a virtual color via the `colors.colorPalette.*` value. This is useful for creating theme components. ``` <Box colorPalette="blue" css={{ "--color": "colors.colorPalette.400" }}> <p style={{ color: "var(--color)" }}>Hello</p> </Box> ``` [Previous \ Responsive Design](https://www.chakra-ui.com/docs/styling/responsive-design) [Next \ Dark Mode](https://www.chakra-ui.com/docs/styling/dark-mode)
https://www.chakra-ui.com/docs/styling/layer-styles
1. Compositions 2. Layer Styles # Layer Styles Learn how to use layer styles to define visual properties. ## [Overview]() Layer styles allows you to define visual properties. The common properties are: - Color or text color - Background color - Border width and border color - Box shadow - Opacity ## [Defining layer styles]() Layer styles are defined using the `defineLayerStyles` function. layer-styles.ts ``` import { defineLayerStyles } from "@chakra-ui/react" const layerStyles = defineLayerStyles({ container: { description: "container styles", value: { bg: "gray.50", border: "2px solid", borderColor: "gray.500", }, }, }) ``` ## [Built-in layer styles]() Chakra UI provides a set of built-in layer styles. layerStyle: fill.* fill.muted fill.subtle fill.surface fill.solid layerStyle: outline.* outline.subtle outline.solid layerStyle: indicator.* indicator.top indicator.bottom indicator.start indicator.end ## [Updating the theme]() To use the layer styles, update the `theme` object with the `layerStyles` property. theme.ts ``` import { createSystem, defineConfig } from "@chakra-ui/react" import { layerStyles } from "./layer-styles" const config = defineConfig({ theme: { layerStyles, }, }) export default createSystem(defaultConfig, config) ``` After updating the theme, run this command to generate the typings. ``` npx @chakra-ui/cli typegen ``` ## [Using layer styles]() Now you can use `layerStyle` property in your components. ``` <Box layerStyle="container">This is inside a container style</Box> ``` [Previous \ Text Styles](https://www.chakra-ui.com/docs/styling/text-styles) [Next \ Animation Styles](https://www.chakra-ui.com/docs/styling/animation-styles)
https://www.chakra-ui.com/docs/styling/cascade-layers
1. Concepts 2. Cascade Layers # Cascade Layers CSS cascade layers refer to the order in which CSS rules are applied to an HTML element. Chakra UI relies on CSS cascade layers to provide a predictable, performant way to override components. The layers are defined to match that of [Panda CSS](https://panda-css.com). **Good to know**: This plays a major role in the faster reconciliation times in v3.x ## [Layer Types]() Chakra supports these cascade layer types: - `@layer reset`: Where the preflight or css resets styles are defined. - `@layer base`: Where global styles are placed when defined in `globalCss` config property. - `@layer recipes`: Where styles for recipes are placed when defined in `theme.recipes` or `theme.slotRecipes` - `@layer tokens`: Where styles for design tokens are placed when defined in `theme.tokens` or `theme.semanticTokens` ## [Layer Order]() Chakra appends the following layers to the top of the generated emotion stylesheet: ``` @layer reset, base, tokens, recipes; ``` This structure allows for smoother experience when combining Chakra and Panda CSS in the same project. ## [Disabling Layers]() Cascade layers are enabled by default. If you want to disable them, you can do so by setting the `disableLayers` option to `true` theme.ts ``` export const system = createSystem(defaultConfig, { disableLayers: true, }) ``` Next, edit the `components/ui/provider` file to use the new system provider.tsx ``` import { ColorModeProvider } from "@/components/ui/color-mode" import { ChakraProvider } from "@chakra-ui/react" import { system } from "./theme" export function Provider(props: React.PropsWithChildren) { return ( <ChakraProvider value={system}> <ColorModeProvider>{props.children}</ColorModeProvider> </ChakraProvider> ) } ``` [Previous \ Virtual Color](https://www.chakra-ui.com/docs/styling/virtual-color) [Next \ Text Styles](https://www.chakra-ui.com/docs/styling/text-styles)
https://www.chakra-ui.com/docs/styling/text-styles
1. Compositions 2. Text Styles # Text Styles Learn how to use text styles to define typography related properties. ## [Overview]() Text styles allows you to define textual css properties. The common properties are: - **Font**: font family, weight, size - **Line height** - **Letter spacing** - **Text decoration** - **Text transform** ## [Defining text styles]() Text styles are defined using the `defineTextStyles` function. ``` import { defineTextStyles } from "@chakra-ui/react" export const textStyles = defineTextStyles({ body: { description: "The body text style - used in paragraphs", value: { fontFamily: "Inter", fontWeight: "500", fontSize: "16px", lineHeight: "24", letterSpacing: "0", textDecoration: "None", textTransform: "None", }, }, }) ``` ## [Built-in text styles]() Chakra UI provides a set of built-in text styles. textStyle: xs Chakra UI textStyle: sm Chakra UI textStyle: md Chakra UI textStyle: lg Chakra UI textStyle: xl Chakra UI textStyle: 2xl Chakra UI textStyle: 3xl Chakra UI textStyle: 4xl Chakra UI textStyle: 5xl Chakra UI textStyle: 6xl Chakra UI textStyle: 7xl Chakra UI ## [Update the theme]() To use the text styles, update the `theme` object with the `textStyles` property. ``` import { createSystem, defineConfig } from "@chakra-ui/react" import { textStyles } from "./text-styles" const config = defineConfig({ theme: { extend: { textStyles, }, }, }) export default createSystem(defaultConfig, config) ``` After updating the theme, run this command to generate the typings. ``` npx @chakra-ui/cli typegen ``` ## [Using text styles]() Now you can use `textStyle` property in your components. ``` <Box textStyle="body">This is the body text style</Box> ``` [Previous \ Cascade Layers](https://www.chakra-ui.com/docs/styling/cascade-layers) [Next \ Layer Styles](https://www.chakra-ui.com/docs/styling/layer-styles)
https://www.chakra-ui.com/docs/styling/virtual-color
1. Concepts 2. Virtual Color # Virtual Color Create color placeholders for better theming and customization. ## [Overview]() Chakra allows you to create a virtual color or color placeholder in your project. The `colorPalette` property is how you create virtual color. ``` <Box colorPalette="blue" bg={{ base: "colorPalette.100", _hover: "colorPalette.200" }} > Hello World </Box> ``` This will translate to the `blue.100` background color and `blue.200` background color on hover. ## [Usage]() The fundamental requirement for virtual colors is that your colors must have a consistent naming convention. By default, Chakra use `50-950` color values for each color we provide. This makes it easier for you to create and use virtual colors. Let's say we need to create a themable outline button from scratch. ``` <chakra.button borderWidth="1px" colorPalette="red" borderColor="colorPalette.500" _hover={{ borderColor: "colorPalette.600", }} > Click me </chakra.button> ``` ### [Recipes]() Virtual colors are most useful when used with recipes. ``` const buttonRecipe = defineRecipe({ base: { display: "flex", alignItems: "center", justifyContent: "center", // set the color palette colorPalette: "blue", }, variants: { variant: { primary: { bg: "colorPalette.500", color: "white", }, outline: { borderWidth: "1px", borderColor: "colorPalette.500", _hover: { borderColor: "colorPalette.600", }, }, }, }, }) ``` ### [Components]() Most built-in components in Chakra support virtual colors. ``` <Button colorPalette="blue">Click me</Button> <Button colorPalette="red" variant="outline"> Click me </Button> ``` ### [Dark mode]() Another amazing thing you can do with virtual colors is to use them with dark mode. ``` <Box colorPalette="blue" bg={{ base: "colorPalette.600", _dark: "colorPalette.400" }} > Hello World </Box> ``` This element will have a `blue.600` background color in light mode and a `blue.400` background color in dark mode. [Previous \ Conditional Styles](https://www.chakra-ui.com/docs/styling/conditional-styles) [Next \ Cascade Layers](https://www.chakra-ui.com/docs/styling/cascade-layers)
https://www.chakra-ui.com/docs/styling/color-opacity-modifier
1. Concepts 2. Color Opacity Modifier # Color opacity modifier How to dynamically set the opacity of a raw color or color token Every color related style property can use the [`color-mix`](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/color-mix) shortcut to apply opacity to a color. ## [Syntax]() The general syntax is `{color}/{opacity}`. For example: `bg="red.300/40"`. ## [Usage]() ``` <Text bg="red.300/40" color="white"> Hello World </Text> ``` This will generate something like this: ``` .css-sxdf { --mix-background: color-mix(in srgb, var(--colors-red-300) 40%, transparent); background: var(--mix-background, var(--colors-red-300)); color: var(--colors-white); } ``` ### [CSS Variables]() This feature can be used in css variables as well. This is useful for creating one-off color token in a component. The token reference syntax `{}` is required for this to work. ``` <Box css={{ "--bg": "{colors.red.400/40}" }}> <Text>Hello World</Text> <Box bg="var(--bg)" /> </Box> ``` [Previous \ Dark Mode](https://www.chakra-ui.com/docs/styling/dark-mode) [Next \ Conditional Styles](https://www.chakra-ui.com/docs/styling/conditional-styles)
https://www.chakra-ui.com/docs/styling/conditional-styles
1. Concepts 2. Conditional Styles # Conditional Styles Learn how to use conditional and responsive styles in Chakra. ## [Overview]() Chakra allows you to write styles for pseudo states, media queries, and custom data attributes with the conditional style props. note See the list of [built-in conditions]() below. ## [Usage]() For example, here's how to change the background color of a button when it's hovered: ``` <Box bg="red.500" _hover={{ bg: "red.700" }}> Hover me </Box> ``` ### [Nested condition]() Conditional values can be nested to create complex selector rules. Here's how to change the background color of an element when in focus on hover: ``` <Box bg={{ base: "red.500", _hover: { _focus: "red.700" } }}> Hover & Focus me </Box> ``` ### [At Rules]() This also works with the supported at-rules (`@media`, `@layer`, `@container`, `@supports`, and `@page`): ``` <Box css={{ "@container (min-width: 10px)": { color: "green.300", }, }} > Hello </Box> ``` ## [Pseudo Classes]() ### [Hover, Active, Focus, and Disabled]() Here's an example of how to style the hover, active, focus, and disabled states of an element ``` <chakra.button _hover={{ bg: "red.700" }} _active={{ bg: "red.900" }} _focus={{ bg: "red.800" }} _disabled={{ opacity: "0.5" }} > Hover me > Hover me </chakra.button> ``` ### [First, Last, Odd, Even]() Here's an example of how to style the first, last, odd, and even elements in a list ``` <Box as="ul"> {items.map((item) => ( <Box as="li" key={item} _first={{ color: "red.500" }} _last={{ color: "red.800" }} > {item} </Box> ))} </Box> ``` You can also style even and odd elements using the `_even` and `_odd` modifier ``` <table> <tbody> {items.map((item) => ( <chakra.tr key={item} _even={{ bg: "gray.100" }} _odd={{ bg: "white" }}> <td>{item}</td> </chakra.tr> ))} </tbody> </table> ``` ## [Pseudo Elements]() ### [Before and After]() To style the `::before` and `::after` pseudo elements of an element, use the `_before` and `_after` modifiers ``` <Box _before={{ content: '"👋"' }} _after={{ content: '"🥂"' }}> Hello </Box> ``` ### [Placeholder]() To style the placeholder text of any input or textarea, use the `_placeholder` modifier: ``` <chakra.input placeholder="Enter your name" _placeholder={{ color: "gray.500" }} /> ``` ### [File Inputs]() To style the file input button, use the `_file` modifier: ``` <chakra.input type="file" _file={{ bg: "gray.500", px: "4", py: "2", marginEnd: "3" }} /> ``` ## [Media Queries]() ### [Reduced Motion]() Use the `_motionReduce` and `_motionSafe` modifiers to style an element based on the user's motion preference: ``` <Box _motionSafe={{ transition: "all 0.3s" }}>Hello</Box> ``` ### [Color Scheme]() The `prefers-color-scheme` media feature is used to detect if the user has requested the system to use a light or dark color theme. Use the `_osLight` and `_osDark` modifiers to style an element based on the user's color scheme preference: ``` <chakra.div bg={{ base: "white", _osDark: "black" }}>Hello</chakra.div> ``` ### [Color Contrast]() The `prefers-contrast` media feature is used to detect if the user has requested the system use a high or low contrast theme. Use the `_highContrast` and `_lessContrast` modifiers to style an element based on the user's color contrast preference: ``` <Box bg={{ base: "white", _highContrast: "black" }}>Hello</Box> ``` ### [Orientation]() The `orientation` media feature is used to detect if the user has a device in portrait or landscape mode. Use the `_portrait` and `_landscape` modifiers to style an element based on the user's device orientation: ``` <Box pb="4" _portrait={{ pb: "8" }}> Hello </Box> ``` ## [Selectors]() ### [Arbitrary selectors]() For arbitrary, use the `css` prop to write styles for one-off selectors: ``` <Box css={{ "&[data-state=closed]": { color: "red.300" } }} /> ``` Here's another example that targets the child elements of a parent element: ``` <Box css={{ "& > *": { margin: "2" }, }} /> ``` ### [Group Selectors]() To style an element based on its parent element's state or attribute, add the `group` class to the parent element, and use any of the `_group*` modifiers on the child element. ``` <div className="group"> <Text _groupHover={{ bg: "red.500" }}>Hover me</Text> </div> ``` This modifier works for every pseudo class modifiers like `_groupHover`, `_groupActive`, `_groupFocus`, and `_groupDisabled`, etc. ### [Sibling Selectors]() To style an element based on its sibling element's state or attribute, add the `peer` class to the sibling element, and use any of the `_peer*` modifiers on the target element. ``` <div> <p className="peer">Hover me</p> <Box _peerHover={{ bg: "red.500" }}>I'll change by bg</Box> </div> ``` **Note:** This only works for when the element marked with `peer` is a previous siblings, that is, it comes before the element you want to start. ## [Data Attribute]() ### [LTR and RTL]() To style an element based on the direction of the text, use the `_ltr` and `_rtl` modifiers ``` <div dir="ltr"> <Box _ltr={{ ml: "3" }} _rtl={{ mr: "3" }}> Hello </Box> </div> ``` ### [State]() To style an element based on its `data-{state}` attribute, use the corresponding `_{state}` modifier ``` <Box data-loading _loading={{ bg: "gray.500" }}> Hello </Box> ``` This works for common states like `data-active`, `data-disabled`, `data-focus`, `data-hover`, `data-invalid`, `data-required`, and `data-valid`. ``` <Box data-active _active={{ bg: "gray.500" }}> Hello </Box> ``` ### [Orientation]() To style an element based on its `data-orientation` attribute, use the `_horizontal` and `_vertical` modifiers ``` <Box data-orientation="horizontal" _horizontal={{ bg: "red.500" }} _vertical={{ bg: "blue.500" }} > Hello </Box> ``` ## [ARIA Attribute]() To style an element based on its `aria-{state}=true` attribute, use the corresponding `_{state}` prop ``` <Box aria-expanded="true" _expanded={{ bg: "gray.500" }}> Hello </Box> ``` ## [Reference]() Here's a list of all the condition props you can use in Chakra: Condition nameSelector`_hover``@media (hover: hover)&:is(:hover, [data-hover]):not(:disabled, [data-disabled])``_active``&:is(:active, [data-active]):not(:disabled, [data-disabled], [data-state=open])``_focus``&:is(:focus, [data-focus])``_focusWithin``&:is(:focus-within, [data-focus-within])``_focusVisible``&:is(:focus-visible, [data-focus-visible])``_disabled``&:is(:disabled, [disabled], [data-disabled], [aria-disabled=true])``_visited``&:visited``_target``&:target``_readOnly``&:is([data-readonly], [aria-readonly=true], [readonly])``_readWrite``&:read-write``_empty``&:is(:empty, [data-empty])``_checked``&:is(:checked, [data-checked], [aria-checked=true], [data-state=checked])``_enabled``&:enabled``_expanded``&:is([aria-expanded=true], [data-expanded], [data-state=expanded])``_highlighted``&[data-highlighted]``_complete``&[data-complete]``_incomplete``&[data-incomplete]``_dragging``&[data-dragging]``_before``&::before``_after``&::after``_firstLetter``&::first-letter``_firstLine``&::first-line``_marker``&::marker``_selection``&::selection``_file``&::file-selector-button``_backdrop``&::backdrop``_first``&:first-of-type``_last``&:last-of-type``_notFirst``&:not(:first-of-type)``_notLast``&:not(:last-of-type)``_only``&:only-child``_even``&:nth-of-type(even)``_odd``&:nth-of-type(odd)``_peerFocus``.peer:is(:focus, [data-focus]) ~ &``_peerHover``.peer:is(:hover, [data-hover]):not(:disabled, [data-disabled]) ~ &``_peerActive``.peer:is(:active, [data-active]):not(:disabled, [data-disabled]) ~ &``_peerFocusWithin``.peer:focus-within ~ &``_peerFocusVisible``.peer:is(:focus-visible, [data-focus-visible]) ~ &``_peerDisabled``.peer:is(:disabled, [disabled], [data-disabled]) ~ &``_peerChecked``.peer:is(:checked, [data-checked], [aria-checked=true], [data-state=checked]) ~ &``_peerInvalid``.peer:is(:invalid, [data-invalid], [aria-invalid=true]) ~ &``_peerExpanded``.peer:is([aria-expanded=true], [data-expanded], [data-state=expanded]) ~ &``_peerPlaceholderShown``.peer:placeholder-shown ~ &``_groupFocus``.group:is(:focus, [data-focus]) &``_groupHover``.group:is(:hover, [data-hover]):not(:disabled, [data-disabled]) &``_groupActive``.group:is(:active, [data-active]):not(:disabled, [data-disabled]) &``_groupFocusWithin``.group:focus-within &``_groupFocusVisible``.group:is(:focus-visible, [data-focus-visible]) &``_groupDisabled``.group:is(:disabled, [disabled], [data-disabled]) &``_groupChecked``.group:is(:checked, [data-checked], [aria-checked=true], [data-state=checked]) &``_groupExpanded``.group:is([aria-expanded=true], [data-expanded], [data-state=expanded]) &``_groupInvalid``.group:invalid &``_indeterminate``&:is(:indeterminate, [data-indeterminate], [aria-checked=mixed], [data-state=indeterminate])``_required``&:is([data-required], [aria-required=true])``_valid``&:is([data-valid], [data-state=valid])``_invalid``&:is([data-invalid], [aria-invalid=true], [data-state=invalid])``_autofill``&:autofill``_inRange``&:is(:in-range, [data-in-range])``_outOfRange``&:is(:out-of-range, [data-outside-range])``_placeholder``&::placeholder, &[data-placeholder]``_placeholderShown``&:is(:placeholder-shown, [data-placeholder-shown])``_pressed``&:is([aria-pressed=true], [data-pressed])``_selected``&:is([aria-selected=true], [data-selected])``_grabbed``&:is([aria-grabbed=true], [data-grabbed])``_underValue``&[data-state=under-value]``_overValue``&[data-state=over-value]``_atValue``&[data-state=at-value]``_default``&:default``_optional``&:optional``_open``&:is([open], [data-open], [data-state=open])``_closed``&:is([closed], [data-closed], [data-state=closed])``_fullscreen``&is(:fullscreen, [data-fullscreen])``_loading``&:is([data-loading], [aria-busy=true])``_hidden``&:is([hidden], [data-hidden])``_current``&[data-current]``_currentPage``&[aria-current=page]``_currentStep``&[aria-current=step]``_today``&[data-today]``_unavailable``&[data-unavailable]``_rangeStart``&[data-range-start]``_rangeEnd``&[data-range-end]``_now``&[data-now]``_topmost``&[data-topmost]``_motionReduce``@media (prefers-reduced-motion: reduce)``_motionSafe``@media (prefers-reduced-motion: no-preference)``_print``@media print``_landscape``@media (orientation: landscape)``_portrait``@media (orientation: portrait)``_dark``.dark &, .dark .chakra-theme:not(.light) &``_light``:root &, .light &``_osDark``@media (prefers-color-scheme: dark)``_osLight``@media (prefers-color-scheme: light)``_highContrast``@media (forced-colors: active)``_lessContrast``@media (prefers-contrast: less)``_moreContrast``@media (prefers-contrast: more)``_ltr``[dir=ltr] &``_rtl``[dir=rtl] &``_scrollbar``&::-webkit-scrollbar``_scrollbarThumb``&::-webkit-scrollbar-thumb``_scrollbarTrack``&::-webkit-scrollbar-track``_horizontal``&[data-orientation=horizontal]``_vertical``&[data-orientation=vertical]``_icon``& :where(svg)``_starting``@starting-style` ## [Customization]() Chakra lets you create your own conditions, so you're not limited to the ones in the default preset. Learn more about customizing conditions [here](https://www.chakra-ui.com/docs/theming/customization/conditions). [Previous \ Color Opacity Modifier](https://www.chakra-ui.com/docs/styling/color-opacity-modifier) [Next \ Virtual Color](https://www.chakra-ui.com/docs/styling/virtual-color)
https://www.chakra-ui.com/playground
Build faster with Premium Chakra UI Components 💎 [Learn more](https://pro.chakra-ui.com?utm_source=chakra-ui.com) [](https://www.chakra-ui.com/) [Docs](https://www.chakra-ui.com/docs/get-started/installation)[Playground](https://www.chakra-ui.com/playground)[Guides](https://www.chakra-ui.com/guides)[Blog](https://www.chakra-ui.com/blog) [](https://github.com/chakra-ui/chakra-ui) [Button]() [View in docs](https://www.chakra-ui.com/docs/components/button) Accent Colors Click Click Click Click Click Click Gray Click Click Click Click Click Click [Code]() [View in docs](https://www.chakra-ui.com/docs/components/code) `console.log()console.log()console.log()console.log()` [Avatar]() [View in docs](https://www.chakra-ui.com/docs/components/avatar) SA![](https://bit.ly/sage-adebayo) DA SA![](https://bit.ly/sage-adebayo) DA [Tabs]() [View in docs](https://www.chakra-ui.com/docs/components/tabs) ComponentsHooksUtilities ComponentsHooksUtilities ComponentsHooksUtilities ComponentsHooksUtilities [Checkbox]() [View in docs](https://www.chakra-ui.com/docs/components/checkbox) Accept terms Accept terms Accept terms Accept terms Accept terms Accept terms [Pagination]() [View in docs](https://www.chakra-ui.com/docs/components/pagination) 1234510 [Radio]() [View in docs](https://www.chakra-ui.com/docs/components/radio) Radio oneRadio second Radio oneRadio second Radio oneRadio second [Rating]() [View in docs](https://www.chakra-ui.com/docs/components/rating) [Switch]() [View in docs](https://www.chakra-ui.com/docs/components/switch) [Blockquote]() [View in docs](https://www.chakra-ui.com/docs/components/blockquote) > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. — Uzumaki Naruto > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. — Uzumaki Naruto [Slider]() [View in docs](https://www.chakra-ui.com/docs/components/slider) [Progress Circle]() [View in docs](https://www.chakra-ui.com/docs/components/progress-circle) [Kbd]() [View in docs](https://www.chakra-ui.com/docs/components/kbd) `⌘ C⌘ C⌘ C` [Spinner]() [View in docs](https://www.chakra-ui.com/docs/components/spinner) [Steps]() [View in docs](https://www.chakra-ui.com/docs/components/steps) 1. 1 Step 1 2. 2 Step 2 3. 3 Step 3 Step 1 Step 2 Step 3 All steps are complete! PrevNext [Timeline]() [View in docs](https://www.chakra-ui.com/docs/components/timeline) Product Shipped 13th May 2021 We shipped your product via **FedEx** and it should arrive within 3-5 business days. Order Confirmed 18th May 2021 Order Delivered 20th May 2021, 10:30am Theme Panel Color Palette Font Family Ag Inter Ag Outfit Ag Geist Ag Figtree Radius none xs sm md lg xl 2xl
https://www.chakra-ui.com/docs/styling/focus-ring
1. Compositions 2. Focus Ring # Focus Ring How to style focus states in Chakra UI The focus ring is used to identify the currently focused element on your page. While this is important for accessibility, styling every component to have a focus ring can be tedious. Chakra UI provides the `focusRing` and `focusVisibleRing` style props to style focus ring with ease. The value of the `focusRing` prop can be "outside", "inside", or "mixed". ## [Focus Ring]() This focus ring maps to the `&:is(:focus, [data-focus])` CSS selector. Here's how to style a button from scratch with a focus ring: ``` <chakra.button px="4" py="2" focusRing="outside"> Click me </chakra.button> ``` ## [Focus Visible Ring]() This focus ring maps to the `&:is(:focus-visible, [data-focus-visible])` CSS selector. ``` <chakra.button px="4" py="2" focusVisibleRing="outside"> Click me </chakra.button> ``` ### [Difference between Focus Ring and Focus Visible Ring]() The Focus Visible Ring functions similarly to the Focus Ring, but with a key difference: it only applies focus indicator styles when an element receives keyboard focus. This ensures that the focus ring is visible only when navigating via keyboard, improving accessibility without affecting mouse interactions. ## [Built-in Focus Ring]() Here's a preview of the supported focus ring. PreviewCode inside outside mixed ``` import { Center, For, Stack } from "@chakra-ui/react" const Demo = () => { return ( <Stack gap="4"> <For each={["inside", "outside", "mixed"]}> {(focusRing) => ( <Center h="20" bg="bg" borderWidth="1px" focusRing={focusRing} data-focus > {focusRing} </Center> )} </For> </Stack> ) } ``` ## [Customization]() ### [Ring Color]() To change the focus ring color for a specific component, you can use the `focusRingColor` prop. ``` <Button focusRingColor="red.500">Click me</Button> ``` To change the color of the focus ring globally, you can configure the `focusRing` semantic token. ``` const colors = defineSemanticTokens.colors({ focusRing: { value: { base: "{colors.red.500}", _dark: "{colors.red.500}" }, }, }) ``` ### [Ring Width]() To change the focus ring width for a specific component, you can use the `focusRingWidth` prop. ``` <Button focusRingWidth="2px">Click me</Button> ``` ### [Ring Style]() To change the focus ring style for a specific component, you can use the `focusRingStyle` prop. ``` <Button focusRingStyle="dashed">Click me</Button> ``` [Previous \ Animation Styles](https://www.chakra-ui.com/docs/styling/animation-styles) [Next \ Background](https://www.chakra-ui.com/docs/styling/style-props/background)
https://www.chakra-ui.com/docs/styling/style-props/display
1. Style Props 2. Display # Display Style props for styling display of an element. ## [Display Property]() ``` <Box display="flex" /> // responsive <Box display={{ base: "none", md: "block" }} /> ``` PropCSS PropertyToken Category`display``display`- ## [Hiding Elements]() ### [Hide From]() Use the `hideFrom` prop to hide an element from a specific breakpoint. ``` <Box display="flex" hideFrom="md" /> ``` PropCSS PropertyToken Category`hideFrom``display``breakpoints` ### [Hide Below]() Use the `hideBelow` prop to hide an element below a specific breakpoint. ``` <Box display="flex" hideBelow="md" /> ``` PropCSS PropertyToken Category`hideBelow``display``breakpoints` [Previous \ Border](https://www.chakra-ui.com/docs/styling/style-props/border) [Next \ Effects](https://www.chakra-ui.com/docs/styling/style-props/effects)
https://www.chakra-ui.com/docs/styling/style-props/effects
1. Style Props 2. Effects # Effects JSX style props for styling box shadows, opacity, and more ## [Box Shadow]() Use the `shadow` or `boxShadow` prop to apply a box shadow to an element. ``` // hardcoded values <Box shadow="12px 12px 2px 1px rgba(0, 0, 255, .2)" /> // token values <Box shadow="lg" /> ``` PropCSS PropertyToken Category`shadows`, `boxShadow``box-shadow``shadows``shadowColor``--shadow-color``colors` ## [Box Shadow Color]() Use the `shadowColor` prop to set the color of a box shadow. This prop maps to the `--shadow-color` CSS variable. ``` <Box shadow="60px -16px var(--shadow-color)" shadowColor="red" /> ``` PropCSS PropertyToken Category`shadowColor``--shadow-color``colors` ## [Opacity]() Use the `opacity` prop to set the opacity of an element. ``` <Box opacity="0.5" /> ``` PropCSS PropertyToken Category`opacity``opacity``opacity` ## [Mix Blend Mode]() Use the `mixBlendMode` prop to control how an element's content should be blended with the background. ``` <Box bg="red.400"> <Image src="..." mixBlendMode="hard-light" /> </Box> ``` PropCSS PropertyToken Category`mixBlendMode``mix-blend-mode`- [Previous \ Display](https://www.chakra-ui.com/docs/styling/style-props/display) [Next \ Filters](https://www.chakra-ui.com/docs/styling/style-props/filters)
https://www.chakra-ui.com/docs/styling/style-props/filters
1. Style Props 2. Filters # Filters JSX style props for applying various filters to elements. ## [Filter]() Use the `filter` prop to apply visual effects like blur or color shift to an element. ``` <Box filter="blur(5px)" /> <Box filter="grayscale(80%)" /> ``` PropCSS PropertyToken Category`filter``filter`- ## [Blur]() Use the `blur` prop to apply a blur effect to an element. The requirement for this prop is to set the `filter` prop to `auto`. ``` // hardcoded value <Box filter="auto" blur="5px" /> // token value <Box filter="auto" blur="sm" /> ``` PropCSS PropertyToken Category`blur``--blur``blurs` ## [Contrast]() Use the `contrast` prop to apply a contrast effect to an element. The requirement for this prop is to use the `filter` prop and set it to `auto`. ``` <Box filter="auto" contrast="0.3" /> ``` PropCSS PropertyToken Category`contrast``--contrast`- ## [Drop Shadow]() Use the `dropShadow` prop to apply a drop shadow effect to an element. The requirement for this prop is to use the `filter` prop and set it to `auto`. ``` <Box filter="auto" dropShadow="0px 0px 10px rgba(0, 0, 0, 0.5)" /> ``` PropCSS PropertyToken Category`dropShadow``--drop-shadow`- ## [Grayscale]() Use the `grayscale` prop to apply a grayscale effect to an element. The requirement for this prop is to use the `filter` prop and set it to `auto`. ``` <Box filter="auto" grayscale="64%" /> ``` PropCSS PropertyToken Category`grayscale``--grayscale`- ## [Hue Rotate]() Use the `hueRotate` prop to apply a hue rotate effect to an element. The requirement for this prop is to use the `filter` prop and set it to `auto`. ``` <Box filter="auto" hueRotate="30deg" /> ``` PropCSS PropertyToken Category`hueRotate``--hue-rotate`- ## [Invert]() Use the `invert` prop to apply an invert effect to an element. The requirement for this prop is to use the `filter` prop and set it to `auto`. ``` <Box filter="auto" invert="40%" /> ``` PropCSS PropertyToken Category`invert``--invert`- ## [Saturate]() Use the `saturate` prop to apply a saturate effect to an element. The requirement for this prop is to use the `filter` prop and set it to `auto`. ``` <Box filter="auto" saturate="0.4" /> ``` PropCSS PropertyToken Category`saturate``--saturate`- ## [Sepia]() Use the `sepia` prop to apply a sepia effect to an element. The requirement for this prop is to use the `filter` prop and set it to `auto`. ``` <Box filter="auto" sepia="0.4" /> ``` PropCSS PropertyToken Category`sepia``--sepia`- ## [Backdrop Filter]() Use the `backdropFilter` prop to apply visual effects like blur or color shift to the area behind an element. This creates a translucent effect. ``` <Box backdropFilter="blur(5px)" /> <Box backdropFilter="grayscale(80%)" /> ``` PropCSS PropertyToken Category`backdropFilter``backdrop-filter`- ## [Backdrop Blur]() Use the `backdropBlur` prop to apply a blur effect to the area behind an element. The requirement for this prop is to set the `backdropFilter` prop to `auto`. ``` // hardcoded value <Box backdropFilter="auto" backdropBlur="5px" /> // token value <Box backdropFilter="auto" backdropBlur="sm" /> ``` PropCSS PropertyToken Category`backdropBlur``--backdrop-blur``blurs` ## [Backdrop Contrast]() Use the `backdropContrast` prop to apply a contrast effect to the area behind an element. The requirement for this prop is to use the `backdropFilter` prop and set it to `auto`. ``` <Box backdropFilter="auto" backdropContrast="0.3" /> ``` PropCSS PropertyToken Category`backdropContrast``--backdrop-contrast`- ## [Backdrop Grayscale]() Use the `backdropGrayscale` prop to apply a grayscale effect to the area behind an element. The requirement for this prop is to use the `backdropFilter` prop and set it to `auto`. ``` <Box backdropFilter="auto" backdropGrayscale="64%" /> ``` PropCSS PropertyToken Category`backdropGrayscale``--backdrop-grayscale`- ## [Backdrop Hue Rotate]() Use the `backdropHueRotate` prop to apply a hue rotate effect to the area behind an element. The requirement for this prop is to use the `backdropFilter` prop and set it to `auto`. ``` <Box backdropFilter="auto" backdropHueRotate="30deg" /> ``` PropCSS PropertyToken Category`backdropHueRotate``--backdrop-hue-rotate`- ## [Backdrop Invert]() Use the `backdropInvert` prop to apply an invert effect to the area behind an element. The requirement for this prop is to use the `backdropFilter` prop and set it to `auto`. ``` <Box backdropFilter="auto" backdropInvert="40%" /> ``` PropCSS PropertyToken Category`backdropInvert``--backdrop-invert`- ## [Backdrop Opacity]() Use the `backdropOpacity` prop to apply an opacity effect to the area behind an element. The requirement for this prop is to use the `backdropFilter` prop and set it to `auto`. ``` <Box backdropFilter="auto" backdropOpacity="0.4" /> ``` PropCSS PropertyToken Category`backdropOpacity``--backdrop-opacity`- ## [Backdrop Saturate]() Use the `backdropSaturate` prop to apply a saturate effect to the area behind an element. The requirement for this prop is to use the `backdropFilter` prop and set it to `auto`. ``` <Box backdropFilter="auto" backdropSaturate="0.4" /> ``` PropCSS PropertyToken Category`backdropSaturate``--backdrop-saturate`- ## [Backdrop Sepia]() Use the `backdropSepia` prop to apply a sepia effect to the area behind an element. The requirement for this prop is to use the `backdropFilter` prop and set it to `auto`. ``` <Box backdropFilter="auto" backdropSepia="0.4" /> ``` PropCSS PropertyToken Category`backdropSepia``--backdrop-sepia`- [Previous \ Effects](https://www.chakra-ui.com/docs/styling/style-props/effects) [Next \ Flex and Grid](https://www.chakra-ui.com/docs/styling/style-props/flex-and-grid)
https://www.chakra-ui.com/docs/styling/style-props/border
1. Style Props 2. Border # Border JSX style props for styling border and border radius. ## [Border Radius]() ### [All sides]() Use the `rounded` or `borderRadius` props to apply border radius on all sides of an element. ``` <Box borderRadius="md" /> <Box rounded="md" /> // shorthand ``` PropCSS PropertyToken Category`rounded`, `borderRadius``border-radius``radii` ### [Specific sides]() Use the `rounded{Left,Right,Top,Bottom}` or `border{Left,Right,Top,Bottom}Radius` prop, to apply border radius on a specific side of an element. ``` <Box borderTopRadius="md" /> <Box roundedTop="md" /> // shorthand <Box borderLeftRadius="md" /> <Box roundedLeft="md" /> // shorthand ``` Use the logical equivalent to make the border radius adapt based on the text direction. ``` <Box roundedStart="md" /> <Box roundedEnd="md" /> ``` PropCSS PropertyToken Category`roundedLeft`, `borderLeftRadius``border-left-radius``radii``roundedRight`, `borderRightRadius``border-right-radius``radii``roundedTop`, `borderTopRadius``border-top-radius``radii``roundedBottom`, `borderBottomRadius``border-bottom-radius``radii``roundedStart`, `borderStartRadius``border-start-start-radius`, `border-end-start-radius``radii``roundedEnd`, `borderEndRadius``border-start-end-radius`, `border-end-end-radius``radii` ### [Specific corners]() Use the `border{Top,Bottom}{Left,Right}Radius` properties, or the shorthand equivalent to round a specific corner. ``` <Box borderTopLeftRadius="md" /> <Box roundedTopLeft="md" /> // shorthand ``` Use the logical properties to adapt based on the text direction. ``` <Box borderStartStartRadius="md" /> <Box roundedStartStart="md" /> // shorthand ``` PropCSS PropertyToken Category`roundedTopLeft`,`borderTopLeftRadius``border-top-left-radius``radii``roundedTopRight`,`borderTopRight``border-top-right-radius``radii``roundedBottomRight`,`borderBottomRight``border-bottom-right-radius``radii``roundedBottomLeft`,`borderBottomLeft``border-bottom-left-radius``radii` ## [Border Width]() ### [All sides]() Use the `borderWidth` prop to apply border width on all sides of an element. Chakra applies `borderStyle: solid` and a global border color by default. Specifying a border width is sufficient to apply the border. ``` <Box borderWidth="1px" /> ``` PropCSS PropertyToken Category`borderWidth``border-width``borderWidths` ### [Specific sides]() Use the `border{Left|Right|Top|Bottom}Width` prop to apply border width on a specific side of an element. ``` <Box borderTopWidth="1px" /> <Box borderLeftWidth="1px" /> ``` Use the logical equivalent to make the border width adapt based on the text direction. ``` <Box borderInlineStartWidth="1px" /> <Box borderInlineWidth="1px" /> // shorthand ``` PropCSS PropertyToken Category`borderTopWidth``border-top-width``borderWidths``borderLeftWidth``border-left-width``borderWidths``borderRightWidth``border-right-width``borderWidths``borderBottomWidth``border-bottom-width``borderWidths``borderStartWidth` , `borderInlineStartWidth``border-{start+end}-width``borderEndWidth` , `borderInlineEndWidth``border-{start+end}-width``borderXWidth` , `borderInlineWidth``border-{left,right}-width``borderWidths``borderYWidth` , `borderBlockWidth``border-{top,bottom}-width``borderWidths` ## [Border Color]() ### [All sides]() Use the `borderColor` prop to apply border color on all sides of an element. ``` <Box borderColor="red.400" /> // with opacity modifier <Box borderColor="red.400/20" /> ``` ### [Specific sides]() Use the `border{Left,Right,Top,Bottom}Color` prop to apply border color on a specific side of an element. ``` <Box borderTopColor="red.400" /> <Box borderLeftColor="red.400" /> ``` Use the logical properties to adapt based on the text direction. ``` <Box borderStartColor="red.400" /> <Box borderEndColor="red.400" /> ``` PropCSS PropertyToken Category`borderColor``border-color``colors``borderTopColor``border-top-color``colors``borderLeftColor``border-left-color``colors``borderRightColor``border-right-color``colors``borderBottomColor``border-bottom-color``colors``borderStartColor` , `borderInlineStartColor``border-{start,end}-color``colors``borderEndColor` , `borderInlineEndColor``border-{start,end}-color``colors``borderXColor`, `borderInlineColor``border-inline-color``colors``borderYColor`, `borderBlockColor``border-block-color``colors` ## [Divide Width]() Use the `divide{X,Y}Width` prop to apply border width between elements. It uses the CSS selector `> * + *` to apply the `border*` properties. ``` <Box divideXWidth="1px"> <Box>1</Box> <Box>2</Box> </Box> <Box divideYWidth="1px"> <Box>1</Box> <Box>2</Box> </Box> ``` PropCSS PropertyToken Category`divideWidth``border-{inline,block}-start-width``borderWidths` ## [Divide Color]() Use the `divideColor` prop to apply border color between elements. ``` <Box divideColor="red.400"> <Box>1</Box> <Box>2</Box> </Box> ``` PropCSS PropertyToken Category`divideColor``--divide-color``colors` ## [Divide Style]() Use the `divideStyle` prop to apply border style between elements. ``` <Box divideX="2px" divideStyle="dashed"> <Box>1</Box> <Box>2</Box> </Box> ``` PropCSS PropertyToken Category`divideStyle``--divide-style``borderStyle` [Previous \ Background](https://www.chakra-ui.com/docs/styling/style-props/background) [Next \ Display](https://www.chakra-ui.com/docs/styling/style-props/display)
https://www.chakra-ui.com/docs/styling/style-props/flex-and-grid
1. Style Props 2. Flex and Grid # Flex and Grid JSX style props to control flex and grid layouts ## [Flex Basis]() Use the `flexBasis` prop to set the initial main size of a flex item. ``` <Flex> <Box flexBasis="25%" /> <Box flexBasis="25%" /> <Box flexBasis="50%" /> </Flex> ``` PropCSS PropertyToken Category`flexBasis``flex-basis`- ## [Flex Direction]() Use the `flexDir` or `flexDirection` prop to set the direction of the main axis in a flex container. ``` <Box display="flex" flexDirection="column"> <Box>Item 1</Box> <Box>Item 2</Box> <Box>Item 3</Box> </Box> ``` When using `Flex` component, the `direction` prop is aliased to `flexDirection`. ``` <Flex direction="column"> <Box>Item 1</Box> <Box>Item 2</Box> <Box>Item 3</Box> </Flex> ``` PropCSS PropertyToken Category`flexDir`, `flexDirection``flex-direction`- ## [Flex Wrap]() Use the `flexWrap` prop to set whether flex items are forced onto one line or can wrap onto multiple lines. ``` <Box display="flex" flexWrap="wrap"> <Box>Item 1</Box> <Box>Item 2</Box> <Box>Item 3</Box> </Box> ``` When using `Flex` component, the `wrap` prop is aliased to `flexWrap`. ``` <Flex wrap="wrap"> <Box>Item 1</Box> <Box>Item 2</Box> <Box>Item 3</Box> </Flex> ``` PropCSS PropertyToken Category`flexWrap``flex-wrap`- ## [Flex]() Use the `flex` prop to define the flexibility of a flex container or item. ``` <Flex> <Box flex="1" /> <Box /> </Flex> ``` PropCSS PropertyToken Category`flex``flex`- ## [Flex Grow]() Use the `flexGrow` prop to set the flex grow factor of a flex item. ``` <Flex> <Box flexGrow="0" /> <Box flexGrow="1" /> </Flex> ``` PropCSS PropertyToken Category`flexGrow``flex-grow`- ## [Flex Shrink]() Use the `flexShrink` prop to set the flex shrink factor of a flex item. ``` <Flex> <Box flexShrink="0" /> <Box flexShrink="1" /> </Flex> ``` PropCSS PropertyToken Category`flexShrink``flex-shrink`- ## [Order]() Use the `order` prop to set the order of a flex item. ``` <Flex> <Box order="0" /> <Box order="1" /> </Flex> ``` PropCSS PropertyToken Category`order``order`- ## [Gap]() Use the `gap` prop to set the gap between items in a flex or grid container. ``` <Flex gap="4"> <Box>Item 1</Box> <Box>Item 2</Box> <Box>Item 3</Box> </Flex> ``` PropCSS PropertyToken Category`gap``gap``spacing` ## [Grid Template Columns]() Use the `gridTemplateColumns` prop to define the columns of a grid container. ``` <Box display="grid" gridTemplateColumns="repeat(3, minmax(0, 1fr))"> <Box>Item 1</Box> <Box>Item 2</Box> <Box>Item 3</Box> </Box> ``` When using `Grid` component, the `templateColumns` prop is aliased to `gridTemplateColumns`. ``` <Grid templateColumns="repeat(3, minmax(0, 1fr))"> <Box>Item 1</Box> <Box>Item 2</Box> <Box>Item 3</Box> </Grid> ``` ## [Grid Template Start/End]() Use the `gridTemplateStart` and `gridTemplateEnd` props to define the start and end of a grid container. ``` <Box display="grid" gridTemplateColumns="repeat(3, minmax(0, 1fr))"> <Box>Item 1</Box> <Box gridColumn="span 2 / span 2">Item 2</Box> <Box>Item 3</Box> </Box> ``` PropCSS PropertyToken Category`gridTemplateStart``grid-template-start`-`gridTemplateEnd``grid-template-end`- ## [Grid Template Rows]() Use the `gridTemplateRows` prop to define the rows of a grid container. ``` <Box display="grid" gap="4" gridTemplateRows="repeat(3, minmax(0, 1fr))"> <Box>Item 1</Box> <Box>Item 2</Box> <Box>Item 3</Box> </Box> ``` PropCSS PropertyToken Category`gridTemplateRows``grid-template-rows`- ## [Grid Row Start/End]() Use the `gridRowStart` and `gridRowEnd` props to define the start and end of a grid item. ``` <Box display="grid" gap="4" gridTemplateRows="repeat(3, minmax(0, 1fr))"> <Box gridRowStart="1" gridRowEnd="3"> Item 1 </Box> <Box>Item 2</Box> <Box>Item 3</Box> </Box> ``` PropCSS PropertyToken Category`gridRowStart``grid-row-start`-`gridRowEnd``grid-row-end`- ## [Grid Autoflow]() Use the `gridAutoFlow` prop to define how auto-placed items get flowed into the grid. ``` <Box display="grid" gridAutoFlow="row"> <Box>Item 1</Box> <Box>Item 2</Box> <Box>Item 3</Box> </Box> ``` PropCSS PropertyToken Category`gridAutoFlow``grid-auto-flow`- ## [Grid Auto Columns]() Use the `gridAutoColumns` prop to specify the size of the grid columns that were created without an explicit size. ``` <Box display="grid" gridAutoColumns="120px"> <Box>Item 1</Box> <Box>Item 2</Box> <Box>Item 3</Box> </Box> ``` PropCSS PropertyToken Category`gridAutoColumns``grid-auto-columns`- ## [Grid Auto Rows]() Use the `gridAutoRows` prop to specify the size of the grid rows that were created without an explicit size. ``` <Box display="grid" gridTemplateRows="200px" gridAutoRows="120px"> <Box>Item 1</Box> <Box>Item 2</Box> <Box>Item 3</Box> </Box> ``` PropCSS PropertyToken Category`gridAutoRows``grid-auto-rows`- ## [Justify Content]() Use the `justifyContent` prop to align items along the main axis of a flex container. ``` <Box display="flex" justifyContent="center"> <Box>Item 1</Box> <Box>Item 2</Box> <Box>Item 3</Box> </Box> ``` When using the `Flex` component, the `justify` prop is aliased to `justifyContent`. ``` <Flex justify="center"> <Box>Item 1</Box> <Box>Item 2</Box> <Box>Item 3</Box> </Flex> ``` PropCSS PropertyToken Category`justifyContent``justify-content`- ## [Justify Items]() Use the `justifyItems` prop to control the alignment of grid items within their scope. ``` <Box display="grid" justifyItems="center"> <Box>Item 1</Box> <Box>Item 2</Box> <Box>Item 3</Box> </Box> ``` PropCSS PropertyToken Category`justifyItems``justify-items`- ## [Align Content]() Use the `alignContent` prop to align rows of content along the cross axis of a flex container when there's extra space. ``` <Box display="flex" alignContent="center"> <Box>Item 1</Box> <Box>Item 2</Box> <Box>Item 3</Box> </Box> ``` When using the `Flex` component, the `align` prop is aliased to `alignContent`. ``` <Flex align="center"> <Box>Item 1</Box> <Box>Item 2</Box> <Box>Item 3</Box> </Flex> ``` PropCSS PropertyToken Category`alignContent``align-content`- ## [Align Items]() Use the `alignItems` prop to control the alignment of grid items within their scope. ``` <Box display="grid" alignItems="center"> <Box>Item 1</Box> <Box>Item 2</Box> <Box>Item 3</Box> </Box> ``` ## [Align Self]() Use the `alignSelf` prop to control the alignment of a grid item within its scope. ``` <Box display="grid"> <Box alignSelf="center">Item 1</Box> <Box>Item 2</Box> <Box>Item 3</Box> </Box> ``` PropCSS PropertyToken Category`alignSelf``align-self`- ## [Place Content]() Use the `placeContent` prop to align content along both the block and inline directions at once. It works like `justifyContent` and `alignContent` combined, and can be used in flex and grid containers. ``` <Flex placeContent="center"> <Box>Item 1</Box> <Box>Item 2</Box> <Box>Item 3</Box> </Flex> ``` PropCSS PropertyToken Category`placeContent``place-content`- ## [Place Items]() Use the `placeItems` prop to align items along both the block and inline directions at once. It works like `justifyItems` and `alignItems` combined, and can be used in flex and grid containers. ``` <Box display="grid" placeItems="center"> <Box>Item 1</Box> <Box>Item 2</Box> <Box>Item 3</Box> </Box> ``` PropCSS PropertyToken Category`placeItems``place-items`- ## [Place Self]() Use the `placeSelf` prop to align a grid item along both the block and inline directions at once. ``` <Box display="grid"> <Box placeSelf="center">Item 1</Box> <Box>Item 2</Box> <Box>Item 3</Box> </Box> ``` PropCSS PropertyToken Category`placeSelf``place-self`- [Previous \ Filters](https://www.chakra-ui.com/docs/styling/style-props/filters) [Next \ Interactivity](https://www.chakra-ui.com/docs/styling/style-props/interactivity)
https://www.chakra-ui.com/docs/styling/animation-styles
1. Compositions 2. Animation Styles # Animation Styles Learn how to use animation styles to define reusable motion properties. ## [Overview]() Animation styles allow you to define reusable animation properties. The goal is to reduce the amount of code needed to animate components. The supported animation styles are: - **Animation**: animation composition, delay, direction, duration, fill mode, iteration count, name, play state, timing function - **Animation range**: animation range, start, end, timeline - **Transform origin**: transform origin ## [Defining animation styles]() Animation styles are defined using the `defineAnimationStyles` function. Here's an example of an animation style: ``` import { defineAnimationStyles } from "@chakra-ui/react" const animationStyles = defineAnimationStyles({ bounceFadeIn: { value: { animationName: "bounce, fade-in", animationDuration: "1s", animationTimingFunction: "ease-in-out", animationIterationCount: "infinite", }, }, }) ``` ## [Built-in animation styles]() Chakra UI provides a set of built-in animation styles that you can use. slide-fade-inslide-fade-outscale-fade-inscale-fade-out Animation ## [Update the theme]() To use the animation styles, update the `theme` object with the `animationStyles` property. ``` import { createSystem, defineConfig } from "@chakra-ui/react" import { animationStyles } from "./animation-styles" const config = defineConfig({ theme: { extend: { animationStyles, }, }, }) export default createSystem(defaultConfig, config) ``` After updating the theme, run this command to generate the animations. ``` npx @chakra-ui/cli typegen ``` These animation styles can be composed with other styles like `_open` and `_closed` which map to the `data-state=open|closed` attribute. ``` <Box data-state="open" animationDuration="slow" animationStyle={{ _open: "slide-fade-in", _closed: "slide-fade-out" }} > > This content will fade in </Box> ``` [Previous \ Layer Styles](https://www.chakra-ui.com/docs/styling/layer-styles) [Next \ Focus Ring](https://www.chakra-ui.com/docs/styling/focus-ring)
https://www.chakra-ui.com/docs/styling/style-props/background
1. Style Props 2. Background # Background JSX style props for styling background colors, gradients, and images. ## [Background Attachment]() Use `bgAttachment` to control the attachment of a background image. ``` <Box bgAttachment="fixed" bgImage="url(...)" /> ``` PropCSS PropertyToken Category`bgAttachment`, `backgroundAttachment``background-attachment`- ## [Background Blend Mode]() Use `bgBlendMode` prop to control how an element's background image should blend with the its background color. ``` <Box bgBlendMode="multiply" bgColor="red.200" bgImage="url(...)" /> ``` ## [Background Clip]() Use `bgClip` to control the clipping of a background image. ``` <Box bgClip="border-box" bgImage="url(...)" /> ``` PropCSS PropertyToken Category`bgClip`, `backgroundClip``background-clip`- ## [Background Color]() Use `bg`, `bgColor`, or `backgroundColor` props to set the background color of an element. ``` <Box bg="red.200" /> <Box bgColor="red.200" /> // with opacity modifier <Box bg="blue.200/30" /> <Box bgColor="blue.200/30" /> ``` PropCSS PropertyToken Category`bg`, `background``background``colors``bgColor`, `backgroundColor``background-color``colors` ## [Background Origin]() Use `bgOrigin` or `backgroundOrigin` to control the origin of a background image. ``` <Box bgOrigin="border-box" bgImage="url(...)" /> ``` PropCSS PropertyToken Category`bgOrigin`, `backgroundOrigin``background-origin`- ## [Background Position]() Properties for controlling the src and position of a background image. ``` <Box bgImage="url(...)" bgPosition="center" /> ``` PropCSS PropertyToken Category`bgPosition`, `backgroundPosition``background-image`-`bgPositionX`, `backgroundPositionX``background-image`-`bgPositionY`, `backgroundPositionY``background-image`- ## [Background Repeat]() Use `bgRepeat` or `backgroundRepeat` to control the repeat of a background image. ``` <Box bgRepeat="no-repeat" bgImage="url(...)" /> ``` PropCSS PropertyToken Category`bgRepeat`, `backgroundRepeat``background-repeat`- ## [Background Size]() Use `bgSize` or `backgroundSize` to control the size of a background image. ``` <Box bgSize="cover" bgImage="url(...)" /> ``` PropCSS PropertyToken Category`bgSize`, `backgroundSize``background-size`- ## [Background Image]() Use `bgImage` or `backgroundImage` to set the background image of an element. ``` <Box bgImage="url(...)" /> <Box bgImage="radial-gradient(circle, #0000 45%, #000f 48%)" /> <Box bgImage="linear-gradient(black, white)" /> // with token reference <Box bgImage="linear-gradient({colors.red.200}, {colors.blue.200})" /> ``` PropCSS PropertyToken Category`bgImage`, `backgroundImage``background-image`assets ## [Background Gradient]() Properties to create a background gradient based on color stops. ``` <Box bgGradient="to-r" gradientFrom="red.200" gradientTo="blue.200" /> ``` PropCSS PropertyToken Category`bgGradient``background-image``gradients``textGradient``background-image``gradients``gradientFrom``--gradient-from``colors``gradientTo``--gradient-to``colors``gradientVia``--gradient-via``colors` [Previous \ Focus Ring](https://www.chakra-ui.com/docs/styling/focus-ring) [Next \ Border](https://www.chakra-ui.com/docs/styling/style-props/border)
https://www.chakra-ui.com/docs/styling/style-props/interactivity
1. Style Props 2. Interactivity # Interactivity JSX style props to enhance interactivity on an element ## [Accent Color]() Use the `accentColor` prop to set the accent color for browser generated user-interface controls. ``` // hardcoded <label> <chakra.input type="checkbox" accentColor="#3b82f6" /> </label> // token value <label> <chakra.input type="checkbox" accentColor="blue.500" /> </label> ``` PropCSS PropertyToken Category`accentColor``accent-color``colors` ## [Appearance]() Use the `appearance` prop to set the appearance of an element. ``` <chakra.select appearance="none"> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> </chakra.select> ``` PropCSS PropertyToken Category`appearance``appearance`- ## [Caret Color]() Use the `caretColor` prop to set the color of the text cursor (caret) in an input or textarea ``` // hardcoded <chakra.input caretColor="#3b82f6" /> // token value <chakra.input caretColor="blue.500" /> ``` PropCSS PropertyToken Category`caretColor``caret-color``colors` ## [Cursor]() Use the `cursor` prop to set the mouse cursor image to show when the mouse pointer is over an element. ``` <Box cursor="pointer" /> ``` PropCSS PropertyToken Category`cursor``cursor`- ## [Pointer Events]() Use the `pointerEvents` prop to control how pointer events are handled on an element. ``` <Box pointerEvents="none">Can't click me</Box> ``` PropCSS PropertyToken Category`pointerEvents``pointer-events`- ## [Resize]() Use the `resize` prop to control whether an element is resizable, and if so, in which directions. ``` <chakra.textarea resize="both" /> <chakra.textarea resize="horizontal" /> <chakra.textarea resize="vertical" /> ``` PropCSS PropertyToken Category`resize``resize`- ## [Scrollbar]() Use the `scrollbar` prop to customize the appearance of scrollbars. ``` <Box scrollbar="hidden" maxH="100px" overflowY="auto"> Scrollbar hidden </Box> ``` ## [Scroll Behavior]() Use the `scrollBehavior` prop to set the behavior for a scrolling box when scrolling is triggered by the navigation or JavaScript code. ``` <Box maxH="100px" overflowY="auto" scrollBehavior="smooth"> <div>Scroll me</div> </Box> ``` PropCSS PropertyToken Category`scrollBehavior``scroll-behavior`- ## [Scroll Margin]() Use the `scrollMargin*` prop to set margins around scroll containers. ``` <Box maxH="100px" overflowY="auto" scrollMarginY="2"> Scrollbar Container with block padding </Box> ``` PropCSS PropertyToken Category`scrollMarginX` ,`scrollMarginInline``scroll-margin-inline``spacing``scrollMarginInlineStart``scroll-margin-inline-start``spacing``scrollMarginInlineEnd``scroll-margin-inline-end``spacing``scrollMarginY` , `scrollMarginBlock``scroll-margin-block``spacing``scrollMarginBlockStart``scroll-margin-block-start``spacing``scrollMarginBlockEnd``scroll-margin-block-end``spacing``scrollMarginLeft``scroll-margin-left``spacing``scrollMarginRight``scroll-margin-right``spacing``scrollMarginTop``scroll-margin-top``spacing``scrollMarginBottom``scroll-margin-bottom``spacing` ## [Scroll Padding]() Use the `scrollPadding*` prop to set padding inside scroll containers. ``` <Box maxH="100px" overflowY="auto" scrollPaddingY="2"> Scrollbar Container with block padding </Box> ``` PropCSS PropertyToken Category`scrollPaddingX` , `scrollPaddingInline``scroll-padding-inline``spacing``scrollPaddingInlineStart``scroll-padding-inline-start``spacing``scrollPaddingInlineEnd``scroll-padding-inline-end``spacing``scrollPaddingY` , `scrollPaddingBlock``scroll-padding-block``spacing``scrollPaddingBlockStart``scroll-padding-block-start``spacing``scrollPaddingBlockEnd``scroll-padding-block-end``spacing``scrollPaddingLeft``scroll-padding-left``spacing``scrollPaddingRight``scroll-padding-right``spacing``scrollPaddingTop``scroll-padding-top``spacing``scrollPaddingBottom``scroll-padding-bottom``spacing` ## [Scroll Snap Margin]() Use the `scrollSnapMargin*` prop to set margins around scroll containers. ``` <Box maxH="100px" overflowY="auto" scrollSnapMarginY="2"> Scrollbar Container with block padding </Box> ``` PropCSS PropertyToken Category`scrollSnapMargin``scroll-margin``spacing``scrollSnapMarginTop``scroll-margin-top``spacing``scrollSnapMarginBottom``scroll-margin-bottom``spacing``scrollSnapMarginLeft``scroll-margin-left``spacing``scrollSnapMarginRight``scroll-margin-right``spacing` ## [Scroll Snap Type]() Use the `scrollSnapType` prop to control how strictly snap points are enforced in a scroll container. ``` <Box maxH="100px" overflowY="auto" scrollSnapType="x"> Scroll container with x snap type </Box> ``` Value`none``none``x``x var(--scroll-snap-strictness)``y``y var(--scroll-snap-strictness)``both``both var(--scroll-snap-strictness)` ## [Scroll Snap Strictness]() Use the `scrollSnapStrictness` prop to set the scroll snap strictness of an element. This requires `scrollSnapType` to be set to `x`,`y` or `both`. It's values can be `mandatory` or `proximity` values, and maps to `var(--scroll-snap-strictness)`. ``` <Box maxH="100px" overflowY="auto" scrollSnapStrictness="proximity"> <Box>Item 1</Box> <Box>Item 2</Box> </Box> ``` PropCSS PropertyToken Category`scrollSnapStrictness``--scroll-snap-strictness`- ## [Touch Action]() Use the `touchAction` prop to control how an element's region can be manipulated by a touchscreen user ``` <Box touchAction="none" /> ``` PropCSS PropertyToken Category`touchAction``touch-action`- ## [User Select]() Use the `userSelect` prop to control whether the user can select text within an element. ``` <Box userSelect="none"> <p>Can't Select me</p> </Box> ``` PropCSS PropertyToken Category`userSelect``user-select`- ## [Will Change]() Use the `willChange` prop to hint browsers how an element's property is expected to change. ``` <Box willChange="transform" /> ``` PropCSS PropertyToken Category`willChange``will-change`- [Previous \ Flex and Grid](https://www.chakra-ui.com/docs/styling/style-props/flex-and-grid) [Next \ Layout](https://www.chakra-ui.com/docs/styling/style-props/layout)
https://www.chakra-ui.com/docs/styling/style-props/layout
1. Style Props 2. Layout # Layout JSX style props to control the width, height, and spacing of elements ## [Aspect Ratio]() Use the `aspectRatio` prop to set the desired aspect ratio of an element. ``` // raw value <Box aspectRatio="1.2" /> // token <Box aspectRatio="square" /> ``` PropCSS PropertyToken Category`aspectRatio``aspect-ratio``aspectRatios` ## [Break]() ### [Break After]() Use the `breakAfter` prop to set how page, column, or region breaks should behave after an element. ``` <Box columns="2"> <Box>Item 1</Box> <Box breakAfter="page">Item 2</Box> </Box> ``` PropCSS PropertyToken Category`breakAfter``break-after`- ### [Break Before]() Use the `breakBefore` prop to set how page, column, or region breaks should behave before an element. ``` <Box columns="2"> <Box>Item 1</Box> <Box breakBefore="page">Item 2</Box> </Box> ``` PropCSS PropertyToken Category`breakBefore``break-before`- ### [Break Inside]() Use the `breakInside` prop to set how page, column, or region breaks should behave inside an element. ``` <Box columns="2"> <Box>Item 1</Box> <Box breakInside="avoid">Item 2</Box> </Box> ``` PropCSS PropertyToken Category`breakInside``break-inside`- ## [Box Decoration Break]() Use the `boxDecorationBreak` prop to set how box decorations should behave when the box breaks across multiple lines, columns, or pages. ``` <Box bgImage="linear-gradient(red, blue)" boxDecorationBreak="clone"> Chakra is <br /> great! </Box> ``` PropCSS PropertyToken Category`boxDecorationBreak``box-decoration-break`- ## [Box Sizing]() Use the `boxSizing` prop to set the box sizing of an element. ``` <Box boxSizing="border-box" padding="4" width="8" height="8" /> ``` PropCSS PropertyToken Category`boxSizing``box-sizing`- ## [Columns]() Use the `columns` prop to set the number of columns for an element. ``` <Box columns={2} /> ``` PropCSS PropertyToken Category`columns``columns`- ## [Float]() Use the `float` prop to set the float of an element. ``` <Box> <Text>As much mud in the streets...</Text> <Box float="left">Float me</Box> </Box> ``` PropCSS PropertyToken Category`float``float`- ## [Clear]() Use the `clear` prop to set whether an element must be moved below (cleared) floating elements that precede it. ``` <Box> <Box float="left">Left</Box> <Box float="right">Right</Box> <Box clear="none"> As much mud in the streets as if the waters had but newly retired from the face of the earth, and it would not be wonderful to meet a Megalosaurus, forty feet long or so, waddling like an elephantine lizard up Holborn Hill. </Box> </Box> ``` PropCSS PropertyToken Category`clear``clear`- ## [Isolation]() Use the `isolation` prop to set whether an element should explicitly create a new stacking context. ``` <Box isolation="isolate"> <Box bg="red.500" width="10" height="10" /> </Box> ``` PropCSS PropertyToken Category`isolation``isolation`- ## [Object Fit]() Use the `objectFit` prop to set how an image or video should be resized to fit its container. ``` <Image src="..." objectFit="cover" width="10" height="10" /> ``` PropCSS PropertyToken Category`objectFit``object-fit`- ## [Object Position]() Use the `objectPosition` prop to set how an element should be positioned within its container. ``` <Image src="..." objectPosition="center" width="10" height="10" /> ``` PropCSS PropertyToken Category`objectPosition``object-position`- ## [Overflow]() Use the `overflow` prop to control how content that exceeds an element's dimensions is handled. This property determines whether to clip the content, add scrollbars, or display the overflow content. ``` <Box overflow="hidden" maxHeight="120px" /> <Box overflow="auto" maxHeight="120px" /> ``` PropCSS PropertyToken Category`overflow``overflow`- ## [Overscroll Behavior]() Use the `overscrollBehavior` prop to control what the browser does when reaching the boundary of a scrolling area. ``` <Box maxHeight="120px" overscrollBehavior="contain" /> ``` PropCSS PropertyToken Category`overscrollBehavior``overscroll-behavior`- ## [Position]() Use the `position` utilities to set the position of an element. ``` <Box position="absolute" /> <Box pos="absolute" /> // shorthand ``` PropCSS PropertyToken Category`position``position`- ## [Top / Right / Bottom / Left]() Use the `top`, `right`, `bottom` and `left` utilities to set the position of an element. ``` <Box position="absolute" top="0" left="0" /> // using spacing tokens <Box position="absolute" top="4" /> // using hardcoded values <Box position="absolute" top="100px" /> ``` Use the logical equivalents of `inset{Start|End}` utilities to set the position of an element based on the writing mode. ``` <Box position="absolute" insetStart="0" /> ``` PropCSS PropertyToken Category`top``top``spacing``right``right``spacing``bottom``bottom``spacing``left``left``spacing``start`, `insetStart`, `insetInlineStart``inset-inline-start``spacing``end` , `insetEnd`, `insetInlineEnd``inset-inline-end``spacing``insetX`, `insetInline``inset-inline``spacing``insetY`, `insetBlock``inset-inline``spacing` ## [Visibility]() Use the `visibility` prop to control the visibility of an element. ``` <Box visibility="hidden" /> ``` PropCSS PropertyToken Category`visibility``visibility`- ## [Z-Index]() Use the `zIndex` prop to set the z-index of an element. ``` // using hardcoded values <Box zIndex="1" /> // using token <Box zIndex="overlay" /> ``` PropCSS PropertyToken Category`zIndex``z-index``zIndices` [Previous \ Interactivity](https://www.chakra-ui.com/docs/styling/style-props/interactivity) [Next \ List](https://www.chakra-ui.com/docs/styling/style-props/list)
https://www.chakra-ui.com/docs/styling/style-props/list
1. Style Props 2. List # List JSX style props for customizing list styles. ## [List Style Type]() Use the `listStyleType` property to set the type of the list marker. ``` <Box as="ul" listStyleType="circle"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </Box> ``` PropCSS PropertyToken Category`listStyleType``list-style-type`- ## [List Style Position]() Use the `listStylePosition` property to set the position of the list marker. ``` <Box as="ul" listStylePosition="inside"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </Box> ``` PropCSS PropertyToken Category`listStylePosition``list-style-position`- ## [List Style Image]() Use the `listStyleImage` property to set the image of the list marker. ``` <Box as="ul" listStyleImage="url(...)"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </Box> ``` PropCSS PropertyToken Category`listStyleImage``list-style-image``assets` ## [Markers]() Use the `_marker` property to set the marker of a list item. ``` <ul> <Box as="li" _marker={{ color: "red" }}> Item 1 </Box> <Box as="li" _marker={{ color: "blue" }}> Item 2 </Box> <Box as="li" _marker={{ color: "green" }}> Item 3 </Box> </ul> ``` [Previous \ Layout](https://www.chakra-ui.com/docs/styling/style-props/layout) [Next \ Sizing](https://www.chakra-ui.com/docs/styling/style-props/sizing)
https://www.chakra-ui.com/docs/styling/style-props/svg
1. Style Props 2. SVG # SVG JSX style props for SVG elements. ## [Fill]() Use the `fill` prop to set the fill color of an SVG element. ``` <chakra.svg fill="blue.500"> <path d="..." /> </chakra.svg> ``` PropCSS PropertyToken Category`fill``fill``colors` ## [Stroke]() Use the `stroke` prop to set the stroke color of an SVG element. ``` <chakra.svg stroke="blue.500"> <path d="..." /> </chakra.svg> ``` PropCSS PropertyToken Category`stroke``stroke``colors` ## [Stroke Width]() Use the `strokeWidth` prop to set the stroke width of an SVG element. ``` <chakra.svg strokeWidth="1px"> <path d="..." /> </chakra.svg> ``` PropCSS PropertyToken Category`strokeWidth``stroke-width``borderWidths` [Previous \ Spacing](https://www.chakra-ui.com/docs/styling/style-props/spacing) [Next \ Tables](https://www.chakra-ui.com/docs/styling/style-props/tables)
https://www.chakra-ui.com/docs/styling/style-props/sizing
1. Style Props 2. Sizing # Sizing JSX style props for sizing an element ## [Width]() Use the `width` or `w` property to set the width of an element. ``` // hardcoded values <Box width="64px" /> <Box w="4rem" /> // token values <Box width="5" /> <Box w="5" /> ``` ### [Fractional width]() Use can set fractional widths using the `width` or `w` property. Values can be within the following ranges: - Thirds: `1/3` to `2/3` - Fourths: `1/4` to `3/4` - Fifths: `1/5` to `4/5` - Sixths: `1/6` to `5/6` - Twelfths: `1/12` to `11/12` ``` // half width <Flex> <Box width="1/2" /> <Box width="1/2" /> </Flex> // thirds <Flex> <Box width="1/3" /> <Box width="2/3" /> </Flex> // fourths <Flex> <Box width="1/4" /> <Box width="3/4" /> </Flex> // fifths <Flex> <Box width="1/5" /> <Box width="4/5" /> </Flex> // sixths <Flex> <Box width="1/6" /> <Box width="5/6" /> </Flex> // twelfths <Flex> <Box width="3/12" /> <Box width="9/12" /> </Flex> ``` ### [Viewport width]() Use the modern viewport width values `dvw`, `svw`, `lvw`. `dvw` maps to `100dvw`, `svw` maps to `100svw`, `lvw` maps to `100lvw`. ``` <Box width="dvw" /> <Box w="dvw" /> // shorthand ``` PropCSS PropertyToken Category`w`, `width``width``sizes` ## [Max width]() Use the `maxWidth` or `maxW` property to set the maximum width of an element. ``` // hardcoded values <Box maxWidth="640px" /> <Box maxW="4rem" /> // shorthand // token values <Box maxWidth="xl" /> <Box maxW="2xl" /> // shorthand ``` PropCSS PropertyToken Category`maxW`, `maxWidth``max-width``sizes` ## [Min width]() Use the `minWidth` or `minW` property to set the minimum width of an element. ``` // hardcoded values <Box minWidth="64px" /> <Box minW="4rem" /> // shorthand // token values <Box minWidth="8" /> <Box minW="10" /> // shorthand ``` PropCSS PropertyToken Category`w`, `width``width``sizing``maxW`, `maxWidth``max-width``sizing``minW`, `minWidth``min-width``sizing` ## [Height]() Use the `height` or `h` property to set the height of an element. ``` // hardcoded values <Box height="40px" /> <Box h="0.4rem" /> // shorthand // token values <Box height="5" /> <Box h="5" /> // shorthand ``` ### [Fractional height]() Use can set fractional heights using the `height` or `h` property. Values can be within the following ranges: - Thirds: `1/3` to `2/3` - Fourths: `1/4` to `3/4` - Fifths: `1/5` to `4/5` - Sixths: `1/6` to `5/6` ``` <Box height="1/2" /> <Box h="1/2" /> // shorthand ``` ### [Relative heights]() Use the modern relative height values `dvh`, `svh`, `lvh`. `dvh` maps to `100dvh`, `svh` maps to `100svh`, `lvh` maps to `100lvh`. ``` <Box height="dvh" /> <Box h="dvh" /> // shorthand ``` ## [Max height]() Use the `maxHeight` or `maxH` property to set the maximum height of an element. ``` // hardcoded values <Box maxHeight="40px" /> <Box maxH="0.4rem" /> // shorthand // token values <Box maxHeight="8" /> <Box maxH="10" /> // shorthand ``` ## [Min height]() Use the `minHeight` or `minH` property to set the minimum height of an element. ``` // hardcoded values <Box minHeight="40px" /> <Box minH="0.4rem" /> // shorthand // token values <Box minHeight="8" /> <Box minH="10" /> // shorthand ``` PropCSS PropertyToken Category`h`, `height``height``sizes``maxH`, `maxHeight``max-height``sizes``minH`, `minHeight``min-height``sizes` [Previous \ List](https://www.chakra-ui.com/docs/styling/style-props/list) [Next \ Spacing](https://www.chakra-ui.com/docs/styling/style-props/spacing)
https://www.chakra-ui.com/docs/styling/style-props/tables
1. Style Props 2. Tables # Tables JSX style props for styling table elements. ## [Border Spacing]() Control the border-spacing property of a table. ``` <chakra.table borderSpacing="2"> <tbody> <tr> <td>Cell 1</td> <td>Cell 2</td> </tr> </tbody> </chakra.table> ``` PropCSS PropertyToken Category`borderSpacing``border-spacing``spacing` ## [Border Spacing X]() Use the `borderSpacingX` prop to set the horizontal border-spacing property of a table. ``` <chakra.table borderSpacingX="2"> <tbody> <tr> <td>Cell 1</td> <td>Cell 2</td> </tr> </tbody> </chakra.table> ``` PropCSS PropertyToken Category`borderSpacingX``border-spacing``spacing` ## [Border Spacing Y]() Use the `borderSpacingY` prop to set the vertical border-spacing property of a table. ``` <chakra.table borderSpacingY="2"> <tbody> <tr> <td>Cell 1</td> <td>Cell 2</td> </tr> </tbody> </chakra.table> ``` PropCSS PropertyToken Category`borderSpacingY``border-spacing``spacing` ## [Caption Side]() Use the `captionSide` prop to set the side of the caption of a table. ``` <table> <chakra.caption captionSide="bottom">This is a caption</chakra.caption> <tbody> <tr> <td>Cell 1</td> <td>Cell 2</td> </tr> </tbody> </table> ``` PropCSS PropertyToken Category`captionSide``caption-side`- [Previous \ SVG](https://www.chakra-ui.com/docs/styling/style-props/svg) [Next \ Transforms](https://www.chakra-ui.com/docs/styling/style-props/transforms)
https://www.chakra-ui.com/docs/styling/style-props/spacing
1. Style Props 2. Spacing # Spacing JSX style props for controlling the padding and margin of an element. ## [Padding]() ### [All sides]() Use the `padding` prop to apply padding on all sides of an element ``` // raw value <Box padding="40px" /> <Box p="40px" /> // shorthand // token value <Box padding="4" /> <Box p="4" /> // shorthand ``` PropCSS PropertyToken Category`p`,`padding``padding``spacing` ### [Specific side]() Use the `padding{Left,Right,Top,Bottom}` to apply padding on one side of an element ``` <Box paddingLeft="3" /> <Box pl="3" /> // shorthand <Box paddingTop="3" /> <Box pt="3" /> // shorthand ``` Use the `padding{Start,End}` props to apply padding on the logical axis of an element based on the text direction. ``` <div className={css({ paddingStart: '8' })} /> <div className={css({ ps: '8' })} /> // shorthand <div className={css({ paddingEnd: '8' })} /> <div className={css({ pe: '8' })} /> // shorthand ``` PropCSS PropertyToken Category`pl`, `paddingLeft``padding-left``spacing``pr`, `paddingRight``padding-right``spacing``pt`, `paddingTop``padding-top``spacing``pb`, `paddingBottom``padding-bottom``spacing``ps`, `paddingStart``padding-inline-start``spacing``pe`, `paddingEnd``padding-inline-end``spacing` ### [Horizontal and Vertical padding]() Use the `padding{X,Y}` props to apply padding on the horizontal and vertical axis of an element ``` <Box paddingX="8" /> <Box px="8" /> // shorthand <Box paddingY="8" /> <Box py="8" /> // shorthand ``` PropCSS PropertyToken Category`p`,`padding``padding``spacing``pl`, `paddingLeft``padding-left``spacing``pr`, `paddingRight``padding-right``spacing``pt`, `paddingTop``padding-top``spacing``pb`, `paddingBottom``padding-bottom``spacing``px`, `paddingX``padding-inline``spacing``py`, `paddingY``padding-block``spacing``ps`, `paddingStart``padding-inline-start``spacing``pe`, `paddingEnd``padding-inline-end``spacing` ## [Margin]() ### [All sides]() Use the `margin` prop to apply margin on all sides of an element ``` <Box margin="5" /> <Box m="5" /> // shorthand ``` PropCSS PropertyToken Category`m`,`margin``margin``spacing` ### [Specific side]() Use the `margin{Left,Right,Top,Bottom}` to apply margin on one side of an element ``` <Box marginLeft="3" /> <Box ml="3" /> // shorthand <Box marginTop="3" /> <Box mt="3" /> // shorthand ``` Use the `margin{Start,End}` properties to apply margin on the logical axis of an element based on the text direction. ``` <Box marginStart="8" /> <Box ms="8" /> // shorthand <Box marginEnd="8" /> <Box me="8" /> // shorthand ``` PropCSS PropertyToken Category`ml`, `marginLeft``margin-left``spacing``mr`, `marginRight``margin-right``spacing``mt`, `marginTop``margin-top``spacing``mb`, `marginBottom``margin-bottom``spacing``ms`, `marginStart``margin-inline-start``spacing``me`, `marginEnd``margin-inline-end``spacing` ### [Horizontal and Vertical margin]() Use the `margin{X,Y}` properties to apply margin on the horizontal and vertical axis of an element ``` <Box marginX="8" /> <Box mx="8" /> // shorthand <Box marginY="8" /> <Box my="8" /> // shorthand ``` PropCSS PropertyToken Category`mx`, `marginX``margin-left``spacing``my`, `marginY``margin-top``spacing` ## [Spacing Between]() Use the `space{X,Y}` props to apply spacing between elements. This approach uses the owl selector `> * + *` to apply the spacing between the elements using `margin*` properties. info It's recommended to use the `space` prop over the `gap` prop for spacing when you need negative spacing. ``` <Box display="flex" spaceX="8"> <Box>Item 1</Box> <Box>Item 2</Box> <Box>Item 3</Box> </Box> <Box display="flex" spaceY="8"> <Box>Item 1</Box> <Box>Item 2</Box> <Box>Item 3</Box> </Box> ``` PropCSS PropertyToken Category`spaceX``margin-inline-start``spacing``spaceY``margin-block-start``spacing` [Previous \ Sizing](https://www.chakra-ui.com/docs/styling/style-props/sizing) [Next \ SVG](https://www.chakra-ui.com/docs/styling/style-props/svg)
https://www.chakra-ui.com/docs/styling/style-props/transforms
1. Style Props 2. Transforms # Transforms JSX style props for transforming elements. ## [Scale]() Use the `scale` prop to control the scale of an element. ``` <Box scale="1.2" /> ``` When the `scale` prop is set to `auto`, the `scaleX` and `scaleY` props are used to control the scale of the element. PropCSS PropertyToken Category`scale``scale`- ## [Scale X]() Use the `scaleX` prop to control the scaleX property of an element. This requires the `scale` prop to be set to `auto`. ``` <Box scale="auto" scaleX="1.3" /> ``` PropCSS PropertyToken Category`scaleX``--scale-x`- ## [Scale Y]() Use the `scaleY` prop to control the scaleY property of an element. This requires the `scale` prop to be set to `auto`. ``` <Box scale="auto" scaleY="0.4" /> ``` PropCSS PropertyToken Category`scaleY``--scale-y`- ## [Rotate]() Use the `rotate` prop to control the rotate property of an element. ``` <Box rotate="45deg" /> ``` When the `rotate` prop is set to `auto`, the `rotateX` and `rotateY` props are used to control the rotate of the element. PropCSS PropertyToken Category`rotate``rotate`- ## [Rotate X]() Use the `rotateX` prop to control the rotateX property of an element. ``` <Box rotateX="45deg" /> ``` PropCSS PropertyToken Category`rotateX``--rotate-x`- ## [Rotate Y]() Use the `rotateY` prop to control the rotateY property of an element. ``` <Box rotateY="45deg" /> ``` PropCSS PropertyToken Category`rotateY``--rotate-y`- ## [Translate]() Use the `translate` prop to control the translate property of an element. ``` <Box translate="40px" /> <Box translate="50% -40%" /> ``` When the `translate` prop is set to `auto`, the `translateX` and `translateY` props are used to control the translate of the element. PropCSS PropertyToken Category`translate``translate`- ## [Translate X]() Use the `translateX` prop to control the translateX property of an element. This requires the `translate` prop to be set to `auto`. ``` // hardcoded values <Box translate="auto" translateX="50%" /> <Box translate="auto" translateX="20px" /> // token values <Box translate="auto" translateX="4" /> <Box translate="auto" translateX="-10" /> ``` PropCSS PropertyToken Category`translateX``--translate-x``spacing` ## [Translate Y]() Use the `translateY` prop to control the translateY property of an element. This requires the `translate` prop to be set to `auto`. ``` // hardcoded values <Box translate="auto" translateY="-40%" /> <Box translate="auto" translateY="4rem" /> // token values <Box translate="auto" translateY="4" /> <Box translate="auto" translateY="-10" /> ``` PropCSS PropertyToken Category`translateY``--translate-y``spacing` [Previous \ Tables](https://www.chakra-ui.com/docs/styling/style-props/tables) [Next \ Transitions](https://www.chakra-ui.com/docs/styling/style-props/transitions)
https://www.chakra-ui.com/docs/components/visually-hidden
1. Utilities 2. Visually Hidden # Visually Hidden Used to hide content visually but keep it accessible to screen readers. PreviewCode 3 Notifications ``` import { Button, VisuallyHidden } from "@chakra-ui/react" import { LuBell } from "react-icons/lu" const Demo = () => { return ( <Button> <LuBell /> 3 <VisuallyHidden>Notifications</VisuallyHidden> </Button> ) } ``` ## [Usage]() ``` import { VisuallyHidden } from "@chakra-ui/react" ``` ``` <VisuallyHidden>Hidden content</VisuallyHidden> ``` ## [Examples]() ### [Input]() Using the `asChild` prop, you can pass a child element to the `VisuallyHidden` component. PreviewCode The input is hidden ``` import { HStack, VisuallyHidden } from "@chakra-ui/react" const Demo = () => { return ( <HStack> The input is hidden <VisuallyHidden asChild> <input type="text" placeholder="Search..." /> </VisuallyHidden> </HStack> ) } ``` [Previous \ Show](https://www.chakra-ui.com/docs/components/show) [Next \ Overview](https://www.chakra-ui.com/docs/styling/overview)
https://www.chakra-ui.com/docs/styling/style-props/transitions
1. Style Props 2. Transitions # Transitions JSX style props for controlling an element's transition and animation. ## [Transition]() Use the `transition` prop to control the transition of an element. ``` // hardcoded value <Box bg="red.400" _hover={{ bg: "red.500" }} transition="background 0.2s ease-in-out"> Hover me </Box> // shortcut value <Box bg="red.400" _hover={{ bg: "red.500" }} transition="backgrounds"> Hover me </Box> ``` PropCSS PropertyToken Category`transition``transition`- ## [Transition Timing Function]() Use the `transitionTimingFunction` prop to control the timing function of a transition. ``` <Box bg="red.400" _hover={{ bg: "red.500" }} transition="backgrounds" transitionTimingFunction="ease-in-out" > Hover me </Box> ``` PropCSS PropertyToken Category`transitionTimingFunction``transition-timing-function``easings` ## [Transition Duration]() Use the `transitionDuration` prop to control the duration of a transition. ``` <Box bg="red.400" _hover={{ bg: "red.500" }} transition="backgrounds" transitionDuration="fast" > Hover me </Box> ``` PropCSS PropertyToken Category`transitionDuration``transition-duration``durations` ## [Transition Delay]() Use the `transitionDelay` prop to control the delay of a transition. ``` <Box bg="red.400" _hover={{ bg: "red.500" }} transition="backgrounds" transitionDelay="fast" > Hover me </Box> ``` PropCSS PropertyToken Category`transitionDelay``transition-delay``durations` ## [Animation]() Use the `animation` prop to control the animation of an element. ``` <Box animation="bounce" /> ``` PropCSS PropertyToken Category`animation``animation-name``animations` ## [Animation Name]() Use the `animationName` prop to control the name of an animation. Compose multiple animation names to create complex animations. info The value of the `animation` prop points to a global keyframe animation. Use the `theme.keyframes` object to define the animation. ``` <Box animationName="bounce, fade-in" animationDuration="fast" /> ``` PropCSS PropertyToken Category`animationName``animation-name``animations` ## [Animation Timing Function]() Use the `animationTimingFunction` prop to control the timing function of an animation. ``` <Box animation="bounce" animationTimingFunction="ease-in-out" /> ``` PropCSS PropertyToken Category`animationTimingFunction``animation-timing-function``easings` ## [Animation Duration]() Use the `animationDuration` prop to control the duration of an animation. ``` <Box animation="bounce" animationDuration="fast" /> ``` PropCSS PropertyToken Category`animationDuration``animation-duration``durations` ## [Animation Delay]() Use the `animationDelay` prop to control the delay of an animation. ``` <Box animation="bounce" animationDelay="fast" /> ``` PropCSS PropertyToken Category`animationDelay``animation-delay``durations` [Previous \ Transforms](https://www.chakra-ui.com/docs/styling/style-props/transforms) [Next \ Typography](https://www.chakra-ui.com/docs/styling/style-props/typography)
https://www.chakra-ui.com/docs/components/concepts/animation
1. Concepts 2. Animation # Animation Using CSS animations to animate Chakra UI components We recommend using CSS animations to animate your Chakra UI components. This approach is performant, straightforward and provides a lot of flexibility. You can animate both the mounting and unmounting phases of your components with better control. ## [Enter animation]() When a disclosure component (popover, dialog) is open, the `data-state` attribute is set to `open`. This maps to `data-state=open` and can be styled with `_open` pseudo prop. ``` <Box data-state="open" _open={{ animation: "fade-in 300ms ease-out", }} > This is open </Box> ``` Here's an example that uses keyframes to create a fade-in animation: ``` @keyframes fade-in { from { opacity: 0; } to { opacity: 1; } } ``` ## [Exit animation]() When a disclosure component (popover, dialog) is closed, the `data-state` attribute is set to `closed`. This maps to `data-state=closed` and can be styled with `_closed` pseudo prop. ``` <Box data-state="closed" _closed={{ animation: "fadeOut 300ms ease-in", }} > This is closed </Box> ``` Here's an example that uses keyframes to create a fade-out animation: ``` @keyframes fadeOut { from { opacity: 1; } to { opacity: 0; } } ``` ## [Composing animations]() Use the `animationName` prop to compose multiple animations together. This makes it easy to create complex animations with multiple keyframes. ``` <Box data-state="open" _open={{ animationName: "fade-in, scale-in", animationDuration: "300ms", }} _closed={{ animationName: "fade-out, scale-out", animationDuration: "120ms", }} > This is a composed animation </Box> ``` [Previous \ Composition](https://www.chakra-ui.com/docs/components/concepts/composition) [Next \ Server Component](https://www.chakra-ui.com/docs/components/concepts/server-components)
https://www.chakra-ui.com/docs/components/aspect-ratio
1. Layout 2. Aspect Ratio # Aspect Ratio Used to embed responsive videos and maps, etc [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/aspect-ratio)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Flayout-aspectratio--responsive) PreviewCode 2 / 1 ``` import { AspectRatio, Center } from "@chakra-ui/react" const Demo = () => { return ( <AspectRatio bg="bg.muted" ratio={2 / 1}> <Center fontSize="xl">2 / 1</Center> </AspectRatio> ) } ``` ## [Usage]() ``` import { AspectRatio } from "@chakra-ui/react" ``` ``` <AspectRatio> <iframe title="naruto" src="https://www.youtube.com/embed/QhBnZ6NPOY0" allowFullScreen /> </AspectRatio> ``` ## [Examples]() ### [Image]() Here's how to embed an image that has a 4 by 3 aspect ratio. PreviewCode ![naruto](https://bit.ly/naruto-sage) ``` import { AspectRatio, Image } from "@chakra-ui/react" const Demo = () => { return ( <AspectRatio maxW="400px" ratio={4 / 3}> <Image src="https://bit.ly/naruto-sage" alt="naruto" objectFit="cover" /> </AspectRatio> ) } ``` ### [Video]() To embed a video with a specific aspect ratio, use an iframe with `src` pointing to the link of the video. PreviewCode ``` import { AspectRatio } from "@chakra-ui/react" const Demo = () => { return ( <AspectRatio maxW="560px" ratio={1}> <iframe title="naruto" src="https://www.youtube.com/embed/QhBnZ6NPOY0" allowFullScreen /> </AspectRatio> ) } ``` ### [Google Map]() Here's how to embed a responsive Google map using `AspectRatio`. PreviewCode ``` import { AspectRatio } from "@chakra-ui/react" const Demo = () => { return ( <AspectRatio ratio={16 / 9}> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3963.952912260219!2d3.375295414770757!3d6.5276316452784755!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x103b8b2ae68280c1%3A0xdc9e87a367c3d9cb!2sLagos!5e0!3m2!1sen!2sng!4v1567723392506!5m2!1sen!2sng" /> </AspectRatio> ) } ``` ### [Responsive]() Here's an example of applying a responsive aspect ratio to a box. PreviewCode Box ``` import { AspectRatio } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" export const AspectRatioResponsive = () => ( <AspectRatio maxWidth="300px" ratio={{ base: 1, md: 16 / 9 }}> <DecorativeBox>Box</DecorativeBox> </AspectRatio> ) ``` ## [Props]() These props can be passed to the `AspectRatio` component. PropDefaultType`ratio` `ConditionalValue<number>` The aspect ratio of the Box. Common values are: \`21/9\`, \`16/9\`, \`9/16\`, \`4/3\`, \`1.85/1\` [Previous \ Server Component](https://www.chakra-ui.com/docs/components/concepts/server-components) [Next \ Bleed](https://www.chakra-ui.com/docs/components/bleed)
https://www.chakra-ui.com/docs/components/concepts/composition
1. Concepts 2. Composition # Composition Learn how to compose components in Chakra UI. ## [The `as` Prop]() Used to change the underlying HTML element that a React component renders. It provides a straightforward way to change the underlying element while retaining the component's functionality. ``` <Heading as="h3">Hello, world!</Heading> ``` warning **TypeScript:** The caveat with the `as` prop is that the types of the component passed to the `as` prop must be compatible with the component's props. We do not infer the underlying component's props from the `as` prop. ## [The `asChild` Prop]() Used to compose a component's functionality onto its child element. This approach, inspired by [Radix UI](https://www.radix-ui.com/primitives/docs/utilities/slot), offers maximum flexibility. ``` <Popover.Root> <Popover.Trigger asChild> <Button>Open</Button> </Popover.Trigger> </Popover.Root> ``` In this example, the `asChild` prop allows the `Button` to be used as the trigger for the popover. ## [Best Practices]() To avoid common pitfalls when using the `as` and `asChild` props, there are a few best practices to consider: - **Forward Refs:** Ensure that the underlying component forwards the ref passed to it properly. - **Spread Props:** Ensure that the underlying component spreads the props passed to it. ``` const MyComponent = React.forwardRef((props, ref) => { return <Box ref={ref} {...props} /> }) // with `as` prop <MyComponent as="button" /> // with `asChild` prop <Button asChild> <MyComponent> Click me </MyComponent> </Button> ``` [Previous \ Overview](https://www.chakra-ui.com/docs/components/concepts/overview) [Next \ Animation](https://www.chakra-ui.com/docs/components/concepts/animation)
https://www.chakra-ui.com/docs/components/concepts/server-components
1. Concepts 2. Server Component # Server Components Learn how to use Chakra UI with React Server Components. React Server Components is a new feature in React that allows you to build components that render on the server and return UI to the client without hydration. Client components are still server-rendered but hydrated on the client. Learn more about [Server component patterns](https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns) Chakra UI components are client components because they rely on `useState`, `useRef` and `useState` which are not available in server components. info **TLDR:** By default, Chakra UI components can be used with React Server Components without adding the 'use client' directive. ## [Usage]() Here's an example of how to use Chakra UI components with React Server Components in Next.js ``` import { Heading } from "@chakra-ui/react" import fs from "node:fs" export default async function Page() { const content = fs.readFileSync("path/to/file.md", "utf-8") return <Heading as="h1">{content}</Heading> } ``` ## [Chakra Factory]() When using the `chakra()` factory function, use the `use client` directive and move the component to a dedicated file. ``` "use client" import { chakra } from "@chakra-ui/react" export const BlogPost = chakra("div", { base: { color: "red", }, variants: { primary: { true: { color: "blue" }, false: { color: "green" }, }, }, }) ``` Then import the component in your page server component ``` import { BlogPost } from "./blog-post" export default async function Page() { const content = fs.readFileSync("path/to/file.md", "utf-8") return <BlogPost>{content}</BlogPost> } ``` ## [Hooks]() When importing hooks from Chakra UI, use the `use client` directive ``` "use client" import { useBreakpointValue } from "@chakra-ui/react" export function MyComponent() { const value = useBreakpointValue({ base: "mobile", md: "desktop" }) return <div>{value}</div> } ``` ## [Render Props]() When using render props, use the `use client` directive ``` "use client" import { ProgressContext } from "@chakra-ui/react" export function MyComponent() { return <ProgressContext>{({ value }) => <div>{value}</div>}</ProgressContext> } ``` [Previous \ Animation](https://www.chakra-ui.com/docs/components/concepts/animation) [Next \ Aspect Ratio](https://www.chakra-ui.com/docs/components/aspect-ratio)
https://www.chakra-ui.com/docs/components/center
1. Layout 2. Center # Center Used to center its child within itself. [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/center)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Flayout-center--basic) PreviewCode This will be centered ``` import { Box, Center } from "@chakra-ui/react" const Demo = () => { return ( <Center bg="bg.emphasized" h="100px" maxW="320px"> <Box>This will be centered</Box> </Center> ) } ``` ## [Usage]() ``` import { AbsoluteCenter, Center, Circle, Square } from "@chakra-ui/react" ``` ``` <Center bg="tomato" h="100px" color="white"> This is the Center </Center> ``` ## [Examples]() ### [Icon]() Center can be used to create frames around icons or numbers. PreviewCode 1 ``` import { Box, Center, HStack } from "@chakra-ui/react" import { LuPhone } from "react-icons/lu" const Demo = () => { return ( <HStack> <Center w="40px" h="40px" bg="tomato" color="white"> <LuPhone /> </Center> <Center w="40px" h="40px" bg="tomato" color="white"> <Box as="span" fontWeight="bold" fontSize="lg"> 1 </Box> </Center> </HStack> ) } ``` ### [Center with Inline]() Use the `inline` to change the display to `inline-flex`. PreviewCode [Visit Chakra UI]() ``` import { Box, Center, Link } from "@chakra-ui/react" import { LuArrowRight } from "react-icons/lu" const Demo = () => { return ( <Link href="#"> <Center inline gap="4"> <Box>Visit Chakra UI</Box> <LuArrowRight /> </Center> </Link> ) } ``` ### [Square]() `Square` centers its child given the `size` (width and height). PreviewCode ``` import { Square } from "@chakra-ui/react" import { LuPhoneForwarded } from "react-icons/lu" const Demo = () => { return ( <Square size="10" bg="purple.700" color="white"> <LuPhoneForwarded /> </Square> ) } ``` ### [Circle]() `Circle` centers its child given the `size` and creates a circle around it. PreviewCode ``` import { Circle } from "@chakra-ui/react" import { LuPhoneForwarded } from "react-icons/lu" const Demo = () => { return ( <Circle size="10" bg="blue.700" color="white"> <LuPhoneForwarded /> </Circle> ) } ``` ### [AbsoluteCenter]() `AbsoluteCenter` centers relative to its parent using the `position: absolute` strategy. Pass the `axis` prop to change the axis of alignment. PreviewCode ``` import { AbsoluteCenter, Box } from "@chakra-ui/react" import { LuPhone } from "react-icons/lu" const Demo = () => { return ( <Box position="relative" h="100px"> <AbsoluteCenter bg="tomato" p="4" color="white" axis="both"> <LuPhone /> </AbsoluteCenter> </Box> ) } ``` ## [Props]() ### [AbsoluteCenter]() PropDefaultType`axis` `'horizontal' | 'vertical' | 'both'` [Previous \ Box](https://www.chakra-ui.com/docs/components/box) [Next \ Container](https://www.chakra-ui.com/docs/components/container)
https://www.chakra-ui.com/docs/components/box
1. Layout 2. Box # Box The most abstract styling component in Chakra UI on top of which all other Chakra UI components are built. PreviewCode This is the Box ``` import { Box } from "@chakra-ui/react" const Demo = () => { return ( <Box background="tomato" width="100%" padding="4" color="white"> This is the Box </Box> ) } ``` ## [Usage]() The `Box` component provides an easy way to write styles with ease. It provides access to design tokens and an unmatched DX when writing responsive styles. ``` import { Box } from "@chakra-ui/react" ``` ``` <Box /> ``` ## [Examples]() ### [Shorthand]() Use shorthand like `bg` instead of `backgroundColor`, `m` instead of `margin`, etc. PreviewCode This is the Box ``` import { Box } from "@chakra-ui/react" const Demo = () => { return ( <Box bg="tomato" w="100%" p="4" color="white"> This is the Box </Box> ) } ``` ### [Pseudo Props]() Use pseudo props like `_hover` to apply styles on hover, `_focus` to apply styles on focus, etc. PreviewCode This is the Box ``` import { Box } from "@chakra-ui/react" const Demo = () => { return ( <Box bg="tomato" w="100%" p="4" color="white" _hover={{ bg: "green" }}> This is the Box </Box> ) } ``` ### [Border]() Use the `borderWidth` and `borderColor` prop to apply border styles. **Good to know:** Chakra applies `borderStyle: solid` globally so you don't have to. PreviewCode Somewhat disabled box ``` import { Box } from "@chakra-ui/react" const Demo = () => { return ( <Box p="4" borderWidth="1px" borderColor="border.disabled" color="fg.disabled" > Somewhat disabled box </Box> ) } ``` ### [As Prop]() Use the `as` prop to render a different component. Inspect the DOM to see the rendered component. PreviewCode This is a Box rendered as a section ``` import { Box } from "@chakra-ui/react" const Demo = () => { return ( <Box as="section" color="fg.muted"> This is a Box rendered as a section </Box> ) } ``` ### [Shadow]() Use the `boxShadow` or `shadow` prop to apply shadow styles. PreviewCode Box with shadow ``` import { Box } from "@chakra-ui/react" const Demo = () => { return ( <Box bg="bg" shadow="md" borderRadius="md"> Box with shadow </Box> ) } ``` ### [Composition]() Here's an example of a property card built with layout primitives in Chakra. PreviewCode ![Rear view of modern home with pool](https://bit.ly/2Z4KKcF) Superhost 4.5 (34) Modern home in city center in the heart of historic Los Angeles $435 • 3 beds ``` import { Badge, Box, HStack, Icon, Image, Text } from "@chakra-ui/react" import { HiStar } from "react-icons/hi" const Demo = () => { return ( <Box maxW="sm" borderWidth="1px"> <Image src={data.imageUrl} alt={data.imageAlt} /> <Box p="4" spaceY="2"> <HStack> <Badge colorPalette="teal" variant="solid"> Superhost </Badge> <HStack gap="1" fontWeight="medium"> <Icon color="orange.400"> <HiStar /> </Icon> <Text> {data.rating} ({data.reviewCount}) </Text> </HStack> </HStack> <Text fontWeight="medium" color="fg"> {data.title} </Text> <HStack color="fg.muted"> {data.formattedPrice} • {data.beds} beds </HStack> </Box> </Box> ) } const data = { imageUrl: "https://bit.ly/2Z4KKcF", imageAlt: "Rear view of modern home with pool", beds: 3, title: "Modern home in city center in the heart of historic Los Angeles", formattedPrice: "$435", reviewCount: 34, rating: 4.5, } ``` ## [Props]() The `Box` component supports all CSS properties as props, making it easy to style elements. [Previous \ Bleed](https://www.chakra-ui.com/docs/components/bleed) [Next \ Center](https://www.chakra-ui.com/docs/components/center)
https://www.chakra-ui.com/docs/components/bleed
1. Layout 2. Bleed # Bleed Used to break an element from the boundaries of its container [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/bleed)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Flayout-bleed--basic) PreviewCode Bleed ## Some Heading Lorem ipsum dolor sit amet, consectetur adipiscing elit. ``` import { Bleed, Box, Heading, Stack, Text } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" const Demo = () => { return ( <Box padding="10" rounded="sm" borderWidth="1px"> <Bleed inline="10"> <DecorativeBox height="20">Bleed</DecorativeBox> </Bleed> <Stack mt="6"> <Heading size="md">Some Heading</Heading> <Text>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</Text> </Stack> </Box> ) } ``` ## [Usage]() ``` import { Bleed } from "@chakra-ui/react" ``` ``` <Bleed> <div /> </Bleed> ``` ## [Examples]() ### [Vertical]() Use the `block` prop to make the element bleed vertically. PreviewCode Bleed ``` import { Bleed, Box } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" const Demo = () => { return ( <Box padding="10" rounded="sm" borderWidth="1px"> <Bleed block="10"> <DecorativeBox height="20">Bleed</DecorativeBox> </Bleed> </Box> ) } ``` ### [Specific Direction]() Use the `inlineStart`, `inlineEnd`, `blockStart`, and `blockEnd` props to make the element bleed in a specific direction. PreviewCode inlineStart inlineEnd blockStart blockEnd ``` import { Bleed, Box, Stack } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" const Demo = () => { return ( <Stack gap="8"> <Box padding="8" rounded="sm" borderWidth="1px"> <Bleed inlineStart="8"> <DecorativeBox height="8">inlineStart</DecorativeBox> </Bleed> </Box> <Box padding="8" rounded="sm" borderWidth="1px"> <Bleed inlineEnd="8"> <DecorativeBox height="8">inlineEnd</DecorativeBox> </Bleed> </Box> <Box padding="8" rounded="sm" borderWidth="1px"> <Bleed blockStart="8"> <DecorativeBox height="8">blockStart</DecorativeBox> </Bleed> </Box> <Box padding="8" rounded="sm" borderWidth="1px"> <Bleed blockEnd="8"> <DecorativeBox height="8">blockEnd</DecorativeBox> </Bleed> </Box> </Stack> ) } ``` ## [Props]() PropDefaultType`inline` `SystemStyleObject['marginInline']` The negative margin on the x-axis `block` `SystemStyleObject['marginBlock']` The negative margin on the y-axis `inlineStart` `SystemStyleObject['marginInlineStart']` The negative margin on the inline-start axis `inlineEnd` `SystemStyleObject['marginInlineEnd']` The negative margin on the inline-end axis `blockStart` `SystemStyleObject['marginBlockStart']` The negative margin on the block-start axis `blockEnd` `SystemStyleObject['marginBlockEnd']` The negative margin on the block-end axis [Previous \ Aspect Ratio](https://www.chakra-ui.com/docs/components/aspect-ratio) [Next \ Box](https://www.chakra-ui.com/docs/components/box)
https://www.chakra-ui.com/docs/components/flex
1. Layout 2. Flex # Flex Used to manage flex layouts [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/flex) PreviewCode ``` import { Flex } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" const Demo = () => { return ( <Flex gap="4"> <DecorativeBox height="10" /> <DecorativeBox height="10" /> <DecorativeBox height="10" /> </Flex> ) } ``` ## [Usage]() ``` import { Flex } from "@chakra-ui/react" ``` ``` <Flex> <div /> <div /> </Flex> ``` ## [Examples]() ### [Direction]() Use the `direction` or `flexDirection` prop to change the direction of the flex PreviewCode ``` import { Flex } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" const Demo = () => { return ( <Flex gap="4" direction="column"> <DecorativeBox height="10" /> <DecorativeBox height="10" /> <DecorativeBox height="10" /> </Flex> ) } ``` ### [Align]() Use the `align` or `alignItems` prop to align the children along the cross axis. PreviewCode ``` import { Flex } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" const Demo = () => { return ( <Flex gap="4" align="center"> <DecorativeBox height="4" /> <DecorativeBox height="8" /> <DecorativeBox height="10" /> </Flex> ) } ``` ### [Justify]() Use the `justify` or `justifyContent` prop to align the children along the main axis. PreviewCode flex-start center flex-end space-between ``` import { Flex } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" const Demo = () => { return ( <Flex direction="column" gap="8"> <Flex gap="4" justify="flex-start"> <DecorativeBox height="10" width="120px" /> <DecorativeBox height="10" width="120px"> flex-start </DecorativeBox> <DecorativeBox height="10" width="120px" /> </Flex> <Flex gap="4" justify="center"> <DecorativeBox height="10" width="120px" /> <DecorativeBox height="10" width="120px"> center </DecorativeBox> <DecorativeBox height="10" width="120px" /> </Flex> <Flex gap="4" justify="flex-end"> <DecorativeBox height="10" width="120px" /> <DecorativeBox height="10" width="120px"> flex-end </DecorativeBox> <DecorativeBox height="10" width="120px" /> </Flex> <Flex gap="4" justify="space-between"> <DecorativeBox height="10" width="120px" /> <DecorativeBox height="10" width="120px"> space-between </DecorativeBox> <DecorativeBox height="10" width="120px" /> </Flex> </Flex> ) } ``` ### [Order]() Use the `order` prop to change the order of the children. PreviewCode 1 2 3 ``` import { Flex } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" const Demo = () => { return ( <Flex gap="4"> <DecorativeBox height="10" order="1"> 1 </DecorativeBox> <DecorativeBox height="10" order="3"> 2 </DecorativeBox> <DecorativeBox height="10" order="2"> 3 </DecorativeBox> </Flex> ) } ``` ### [Auto Margin]() Apply margin to a flex item to push it away from its siblings. PreviewCode ``` import { Flex } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" const Demo = () => { return ( <Flex gap="4" justify="space-between"> <DecorativeBox height="10" width="40" /> <DecorativeBox height="10" width="40" marginEnd="auto" /> <DecorativeBox height="10" width="40" /> </Flex> ) } ``` ### [Wrap]() Use the `wrap` or `flexWrap` prop to wrap the children when they overflow the parent. PreviewCode ``` import { Flex } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" const Demo = () => { return ( <Flex gap="4" wrap="wrap" maxW="500px"> <DecorativeBox height="10" width="200px" /> <DecorativeBox height="10" width="200px" /> <DecorativeBox height="10" width="200px" /> </Flex> ) } ``` ## [Props]() PropDefaultType`align` `SystemStyleObject['alignItems']` `justify` `SystemStyleObject['justifyContent']` `wrap` `SystemStyleObject['flexWrap']` `direction` `SystemStyleObject['flexDirection']` `basis` `SystemStyleObject['flexBasis']` `grow` `SystemStyleObject['flexGrow']` `shrink` `SystemStyleObject['flexShrink']` `inline` `boolean` [Previous \ Container](https://www.chakra-ui.com/docs/components/container) [Next \ Float](https://www.chakra-ui.com/docs/components/float)
https://www.chakra-ui.com/docs/components/container
1. Layout 2. Container # Container Used to constrain a content's width to the current breakpoint, while keeping it fluid. [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/container)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Flayout-container--basic)[Recipe](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/theme/recipes/container.ts) PreviewCode Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam consectetur, tortor in lacinia eleifend, dui nisl tristique nunc. ``` import { Container } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" const Demo = () => { return ( <Container> <DecorativeBox px="2"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam consectetur, tortor in lacinia eleifend, dui nisl tristique nunc. </DecorativeBox> </Container> ) } ``` ## [Usage]() The default `maxWidth` is `8xl` which maps to `90rem (1440px)`. ``` import { Container } from "@chakra-ui/react" ``` ``` <Container> <div /> </Container> ``` ## [Examples]() ### [Sizes]() Use the `maxWidth` prop to change the size of the container. PreviewCode Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam consectetur, tortor in lacinia eleifend, dui nisl tristique nunc. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam consectetur, tortor in lacinia eleifend, dui nisl tristique nunc. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam consectetur, tortor in lacinia eleifend, dui nisl tristique nunc. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam consectetur, tortor in lacinia eleifend, dui nisl tristique nunc. ``` import { Container, For, Stack } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" const Demo = () => { return ( <Stack> <For each={["sm", "md", "xl", "2xl"]}> {(size) => ( <Container key={size} maxW={size} px="2"> <DecorativeBox> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam consectetur, tortor in lacinia eleifend, dui nisl tristique nunc. </DecorativeBox> </Container> )} </For> </Stack> ) } ``` ### [Fluid]() Use the `fluid` prop to make the container stretch to fill the width of its parent. PreviewCode Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam consectetur, tortor in lacinia eleifend, dui nisl tristique nunc. ``` import { Container } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" const Demo = () => { return ( <Container fluid> <DecorativeBox px="2"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam consectetur, tortor in lacinia eleifend, dui nisl tristique nunc. </DecorativeBox> </Container> ) } ``` ## [Props]() PropDefaultType`colorPalette``'gray'` `'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink' | 'accent'` The color palette of the component `centerContent` `'true' | 'false'` The centerContent of the component `fluid` `'true' | 'false'` The fluid of the component [Previous \ Center](https://www.chakra-ui.com/docs/components/center) [Next \ Flex](https://www.chakra-ui.com/docs/components/flex)
https://www.chakra-ui.com/docs/components/float
1. Layout 2. Float # Float Used to anchor an element to the edge of a container. [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/float)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Fcomponents-float--basic) PreviewCode 3 ``` import { Box, Circle, Float } from "@chakra-ui/react" export const FloatBasic = () => ( <Box position="relative" w="80px" h="80px" bg="bg.emphasized"> <Float> <Circle size="5" bg="red" color="white"> 3 </Circle> </Float> </Box> ) ``` ## [Usage]() Float requires a parent element with `position: relative` style applied. ``` import { Box, Float } from "@chakra-ui/react" ``` ``` <Box position="relative"> <Float> <div /> </Float> </Box> ``` ## [Examples]() ### [Placement]() Use the `placement` prop to position the element along the edges of the container. PreviewCode bottom-end 3 bottom-start 3 top-end 3 top-start 3 bottom-center 3 top-center 3 middle-center 3 middle-end 3 middle-start 3 ``` import { Box, Circle, Float, HStack, Stack } from "@chakra-ui/react" export const FloatWithPlacements = () => ( <HStack gap="14" wrap="wrap"> {placements.map((placement) => ( <Stack key={placement} gap="3"> <p>{placement}</p> <Box position="relative" width="80px" height="80px" bg="bg.emphasized"> <Float placement={placement}> <Circle size="5" bg="red" color="white"> 3 </Circle> </Float> </Box> </Stack> ))} </HStack> ) const placements = [ "bottom-end", "bottom-start", "top-end", "top-start", "bottom-center", "top-center", "middle-center", "middle-end", "middle-start", ] as const ``` ### [Offset X]() Use the `offsetX` prop to offset the element along the x-axis. PreviewCode 3 ``` import { Box, Circle, Float } from "@chakra-ui/react" export const FloatWithOffsetX = () => ( <Box position="relative" w="80px" h="80px" bg="bg.emphasized"> <Float offsetX="-4"> <Circle size="5" bg="red" color="white"> 3 </Circle> </Float> </Box> ) ``` ### [Offset Y]() Use the `offsetY` prop to offset the element along the y-axis. PreviewCode 3 ``` import { Box, Circle, Float } from "@chakra-ui/react" export const FloatWithOffsetY = () => ( <Box position="relative" w="80px" h="80px" bg="bg.emphasized"> <Float offsetY="-4"> <Circle size="5" bg="red" color="white"> 3 </Circle> </Float> </Box> ) ``` ### [Offset]() Use the `offset` prop to offset the element along both axes. PreviewCode 3 ``` import { Box, Circle, Float } from "@chakra-ui/react" export const FloatWithOffset = () => ( <Box position="relative" w="80px" h="80px" bg="bg.emphasized"> <Float offset="4"> <Circle size="5" bg="red" color="white"> 3 </Circle> </Float> </Box> ) ``` ### [Avatar]() Here's an example of composing a `Float` component with an `Avatar` component. PreviewCode ![](https://bit.ly/dan-abramov) New ``` import { Badge, Box, Float } from "@chakra-ui/react" import { Avatar } from "@/components/ui/avatar" const Demo = () => { return ( <Box display="inline-block" pos="relative"> <Avatar size="lg" shape="rounded" src="https://bit.ly/dan-abramov" /> <Float placement="bottom-end"> <Badge size="sm" variant="solid" colorPalette="teal"> New </Badge> </Float> </Box> ) } ``` ## [Props]() PropDefaultType`placement``'top-end'` `ConditionalValue< | 'bottom-end' | 'bottom-start' | 'top-end' | 'top-start' | 'bottom-center' | 'top-center' | 'middle-center' | 'middle-end' | 'middle-start' >` The placement of the indicator `offsetX` `SystemStyleObject['left']` The x offset of the indicator `offsetY` `SystemStyleObject['top']` The y offset of the indicator `offset` `SystemStyleObject['top']` The x and y offset of the indicator [Previous \ Flex](https://www.chakra-ui.com/docs/components/flex) [Next \ Grid](https://www.chakra-ui.com/docs/components/grid)
https://www.chakra-ui.com/docs/components/group
1. Layout 2. Group # Group Used to group and attach elements together [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/group)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Fcomponents-group--basic) PreviewCode 1 2 ``` import { Group } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" const Demo = () => { return ( <Group> <DecorativeBox h="20" w="40"> 1 </DecorativeBox> <DecorativeBox h="20" w="40"> 2 </DecorativeBox> </Group> ) } ``` ## [Usage]() ``` import { Group } from "@chakra-ui/react" ``` ``` <Group> <div /> <div /> </Group> ``` ## [Examples]() ### [Button]() Here's an example of using the `Group` component to group buttons together. PreviewCode Item 1Item 2 ``` import { Button, Group } from "@chakra-ui/react" const Demo = () => { return ( <Group> <Button variant="outline">Item 1</Button> <Button variant="outline">Item 2</Button> </Group> ) } ``` ### [Attached]() Use the `attached` prop to attach the children together. PreviewCode Item 1Item 2 Commit status90+ ``` import { Badge, Button, Group, Stack } from "@chakra-ui/react" const Demo = () => { return ( <Stack gap="4"> <Group attached> <Button variant="outline">Item 1</Button> <Button variant="outline">Item 2</Button> </Group> <Group attached> <Badge variant="solid" colorPalette="purple"> Commit status </Badge> <Badge variant="solid" colorPalette="green"> 90+ </Badge> </Group> </Stack> ) } ``` ### [Grow]() Use the `grow` prop to make the children grow to fill the available space. PreviewCode FirstSecondThird ``` import { Button, Group } from "@chakra-ui/react" const Demo = () => { return ( <Group grow> <Button variant="outline">First</Button> <Button variant="outline">Second</Button> <Button variant="outline">Third</Button> </Group> ) } ``` ## [Props]() [Previous \ Grid](https://www.chakra-ui.com/docs/components/grid) [Next \ SimpleGrid](https://www.chakra-ui.com/docs/components/simple-grid)
https://www.chakra-ui.com/docs/components/grid
1. Layout 2. Grid # Grid Used to manage grid layouts [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/grid)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Fcomponents-grid--basic) PreviewCode ``` import { Grid } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" const Demo = () => { return ( <Grid templateColumns="repeat(3, 1fr)" gap="6"> <DecorativeBox h="20" /> <DecorativeBox h="20" /> <DecorativeBox h="20" /> </Grid> ) } ``` ## [Usage]() ``` import { Grid, GridItem } from "@chakra-ui/react" ``` ``` <Grid> <GridItem /> <GridItem /> </Grid> ``` ## [Examples]() ### [Col Span]() Pass `colSpan` prop to `GridItem` to span across columns. PreviewCode ``` import { Grid, GridItem } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" const Demo = () => { return ( <Grid templateColumns="repeat(4, 1fr)" gap="6"> <GridItem colSpan={2}> <DecorativeBox h="20" /> </GridItem> <GridItem colSpan={1}> <DecorativeBox h="20" /> </GridItem> <GridItem colSpan={1}> <DecorativeBox h="20" /> </GridItem> </Grid> ) } ``` ### [Spanning Columns]() In some layouts, you may need certain grid items to span specific amount of columns or rows instead of an even distribution PreviewCode rowSpan=2 colSpan=2 colSpan=2 colSpan=4 ``` import { Grid, GridItem } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" const Demo = () => { return ( <Grid h="200px" templateRows="repeat(2, 1fr)" templateColumns="repeat(5, 1fr)" gap={4} > <GridItem rowSpan={2} colSpan={1}> <DecorativeBox>rowSpan=2</DecorativeBox> </GridItem> <GridItem colSpan={2}> <DecorativeBox>colSpan=2</DecorativeBox> </GridItem> <GridItem colSpan={2}> <DecorativeBox>colSpan=2</DecorativeBox> </GridItem> <GridItem colSpan={4}> <DecorativeBox>colSpan=4</DecorativeBox> </GridItem> </Grid> ) } ``` ## [Props]() PropDefaultType`templateColumns` `SystemStyleObject['gridTemplateColumns']` `autoFlow` `SystemStyleObject['gridAutoFlow']` `autoRows` `SystemStyleObject['gridAutoRows']` `autoColumns` `SystemStyleObject['gridAutoColumns']` `templateRows` `SystemStyleObject['gridTemplateRows']` `templateAreas` `SystemStyleObject['gridTemplateAreas']` `column` `SystemStyleObject['gridColumn']` `row` `SystemStyleObject['gridRow']` `inline` `boolean` [Previous \ Float](https://www.chakra-ui.com/docs/components/float) [Next \ Group](https://www.chakra-ui.com/docs/components/group)
https://www.chakra-ui.com/docs/components/simple-grid
1. Layout 2. SimpleGrid # SimpleGrid SimpleGrid provides a friendly interface to create responsive grid layouts with ease. PreviewCode ``` import { SimpleGrid } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" const Demo = () => { return ( <SimpleGrid columns={2} gap="40px"> <DecorativeBox height="20" /> <DecorativeBox height="20" /> <DecorativeBox height="20" /> <DecorativeBox height="20" /> </SimpleGrid> ) } ``` ## [Usage]() The `SimpleGrid` component allows you to create responsive grid layouts with ease. ``` import { SimpleGrid } from "@chakra-ui/react" ``` ``` <SimpleGrid> <Box /> <Box /> </SimpleGrid> ``` ## [Examples]() ### [Columns]() Specify the number of columns for the grid layout using the `columns` prop. PreviewCode ``` import { SimpleGrid } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" export const SimpleGridWithColumns = () => ( <SimpleGrid columns={[2, null, 3]} gap="40px"> <DecorativeBox height="20" /> <DecorativeBox height="20" /> <DecorativeBox height="20" /> <DecorativeBox height="20" /> <DecorativeBox height="20" /> </SimpleGrid> ) ``` ### [Auto-responsive]() Make the grid responsive and adjust automatically without passing columns, by using the `minChildWidth` prop. This uses css grid auto-fit and minmax() internally. PreviewCode ``` import { SimpleGrid } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" export const SimpleGridWithAutofit = () => ( <SimpleGrid minChildWidth="sm" gap="40px"> <DecorativeBox height="20" /> <DecorativeBox height="20" /> <DecorativeBox height="20" /> <DecorativeBox height="20" /> <DecorativeBox height="20" /> </SimpleGrid> ) ``` ### [Column Span]() Specify the size of the column by using the `colSpan` prop. PreviewCode Column 1 Column 2 ``` import { GridItem, SimpleGrid } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" export const SimpleGridWithColSpan = () => ( <SimpleGrid columns={{ base: 2, md: 4 }} gap={{ base: "24px", md: "40px" }}> <GridItem colSpan={{ base: 1, md: 3 }}> <DecorativeBox height="20">Column 1</DecorativeBox> </GridItem> <GridItem colSpan={{ base: 1, md: 1 }}> <DecorativeBox height="20">Column 2</DecorativeBox> </GridItem> </SimpleGrid> ) ``` ### [Row and Column Gap]() Pass the `rowGap` and `columnGap` props to change the row and column spacing between the grid items. PreviewCode ``` import { SimpleGrid } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" const Demo = () => { return ( <SimpleGrid columns={2} columnGap="2" rowGap="4"> <DecorativeBox height="20" /> <DecorativeBox height="20" /> <DecorativeBox height="20" /> <DecorativeBox height="20" /> </SimpleGrid> ) } ``` [Previous \ Group](https://www.chakra-ui.com/docs/components/group) [Next \ Stack](https://www.chakra-ui.com/docs/components/stack)
https://www.chakra-ui.com/docs/components/stack
1. Layout 2. Stack # Stack Used to layout its children in a vertical or horizontal stack. [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/stack) PreviewCode ``` import { Stack } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" const Demo = () => { return ( <Stack> <DecorativeBox h="20" /> <DecorativeBox h="20" /> <DecorativeBox h="20" /> </Stack> ) } ``` ## [Usage]() By default, Stack applies `flex-direction: column` and `gap: 8px` to its children. ``` import { HStack, Stack, VStack } from "@chakra-ui/react" ``` ``` <Stack> <div /> <div /> </Stack> ``` ## [Examples]() ### [Horizontal]() Use the `direction` prop to change the direction of the stack. PreviewCode ``` import { Stack } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" const Demo = () => { return ( <Stack direction="row" h="20"> <DecorativeBox /> <DecorativeBox /> <DecorativeBox /> </Stack> ) } ``` ### [HStack]() Alternatively, you can use the `HStack` to create a horizontal stack and align its children horizontally. PreviewCode ``` import { HStack } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" const Demo = () => { return ( <HStack> <DecorativeBox h="10" /> <DecorativeBox h="5" /> <DecorativeBox h="20" /> </HStack> ) } ``` ### [VStack]() Use the `VStack` to create a vertical stack and align its children vertically. PreviewCode ``` import { VStack } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" const Demo = () => { return ( <VStack> <DecorativeBox w="50%" h="20" /> <DecorativeBox w="25%" h="20" /> <DecorativeBox w="100%" h="20" /> </VStack> ) } ``` ### [Separator]() Use the `separator` prop to add a separator between the stack items. PreviewCode ``` import { Stack, StackSeparator } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" const Demo = () => { return ( <Stack separator={<StackSeparator />}> <DecorativeBox h="20" /> <DecorativeBox h="20" /> <DecorativeBox h="20" /> </Stack> ) } ``` ### [Responsive Direction]() Use the `direction` prop to change the direction of the stack responsively. PreviewCode ``` import { Stack } from "@chakra-ui/react" import { DecorativeBox } from "compositions/lib/decorative-box" const Demo = () => { return ( <Stack direction={{ base: "column", md: "row" }} gap="10"> <DecorativeBox boxSize="20" /> <DecorativeBox boxSize="20" /> <DecorativeBox boxSize="20" /> </Stack> ) } ``` [Previous \ SimpleGrid](https://www.chakra-ui.com/docs/components/simple-grid) [Next \ Theme](https://www.chakra-ui.com/docs/components/theme)
https://www.chakra-ui.com/docs/components/code
1. Typography 2. Code # Code Used to display inline code [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/code)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Ftypography-code--basic)[Recipe](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/theme/recipes/code.ts) PreviewCode `console.log("Hello, world!")` ``` import { Code } from "@chakra-ui/react" const Demo = () => { return <Code>{`console.log("Hello, world!")`}</Code> } ``` ## [Usage]() ``` import { Code } from "@chakra-ui/react" ``` ``` <Code>Hello world</Code> ``` ## [Examples]() ### [Sizes]() Use the `size` prop to change the size of the code component. PreviewCode `console.log()console.log()console.log()console.log()` ``` import { Code, Stack } from "@chakra-ui/react" const Demo = () => { return ( <Stack gap="2" align="flex-start"> <Code size="xs">console.log()</Code> <Code size="sm">console.log()</Code> <Code size="md">console.log()</Code> <Code size="lg">console.log()</Code> </Stack> ) } ``` ### [Variants]() Use the `variant` prop to change the appearance of the code component. PreviewCode `console.log()console.log()console.log()console.log()` ``` import { Code, Stack } from "@chakra-ui/react" const Demo = () => { return ( <Stack gap="2" align="flex-start"> <Code variant="solid">console.log()</Code> <Code variant="outline">console.log()</Code> <Code variant="subtle">console.log()</Code> <Code variant="surface">console.log()</Code> </Stack> ) } ``` ### [Colors]() Use the `colorPalette` prop to change the color scheme of the component. PreviewCode gray `console.log()console.log()console.log()console.log()` red `console.log()console.log()console.log()console.log()` green `console.log()console.log()console.log()console.log()` blue `console.log()console.log()console.log()console.log()` teal `console.log()console.log()console.log()console.log()` pink `console.log()console.log()console.log()console.log()` purple `console.log()console.log()console.log()console.log()` cyan `console.log()console.log()console.log()console.log()` orange `console.log()console.log()console.log()console.log()` yellow `console.log()console.log()console.log()console.log()` ``` import { Code, Stack, Text } from "@chakra-ui/react" import { colorPalettes } from "compositions/lib/color-palettes" const Demo = () => { return ( <Stack gap="2" align="flex-start"> {colorPalettes.map((colorPalette) => ( <Stack align="center" key={colorPalette} direction="row" gap="10" px="4" width="full" > <Text minW="8ch" textStyle="sm"> {colorPalette} </Text> <Code colorPalette={colorPalette} variant="solid"> {`console.log()`} </Code> <Code colorPalette={colorPalette} variant="outline"> {`console.log()`} </Code> <Code colorPalette={colorPalette} variant="subtle"> {`console.log()`} </Code> <Code colorPalette={colorPalette} variant="surface"> {`console.log()`} </Code> </Stack> ))} </Stack> ) } ``` ## [Props]() PropDefaultType`colorPalette``'gray'` `'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink' | 'accent'` The color palette of the component `variant``'subtle'` `'solid' | 'subtle' | 'outline' | 'surface' | 'plain'` The variant of the component `size``'sm'` `'xs' | 'sm' | 'md' | 'lg'` The size of the component [Previous \ Blockquote](https://www.chakra-ui.com/docs/components/blockquote) [Next \ Em](https://www.chakra-ui.com/docs/components/em)
https://www.chakra-ui.com/docs/components/theme
1. Layout 2. Theme # Theme Used to force a part of the tree to light or dark mode. PreviewCode Auto Button Dark Button Light Button ``` import { Button, Stack, Theme } from "@chakra-ui/react" const Demo = () => { return ( <Stack align="flex-start"> <Button variant="surface" colorPalette="teal"> Auto Button </Button> <Theme p="4" appearance="dark" colorPalette="teal"> <Button variant="surface">Dark Button</Button> </Theme> <Theme p="4" appearance="light" colorPalette="teal"> <Button variant="surface">Light Button</Button> </Theme> </Stack> ) } ``` ## [Usage]() ``` import { Theme } from "@chakra-ui/react" ``` ``` <Theme appearance="dark"> <div /> </Theme> ``` ## [Examples]() ### [Nested]() The theme can be nested to apply different appearances to different parts of the tree. This is useful for applying a global appearance and then overriding some parts of it. Good to know: We use native CSS selectors to achieve this. PreviewCode Hello Normal Click me Hello Dark Click me Hello Light Click me ``` import { Box, Button, Theme } from "@chakra-ui/react" const Demo = () => { return ( <Box> <Box p="8" borderWidth="1px"> Hello Normal <Button>Click me</Button> <Theme appearance="dark" colorPalette="red"> <Box p="8" borderWidth="1px"> Hello Dark <Button>Click me</Button> <Theme appearance="light" colorPalette="pink"> <Box p="8" borderWidth="1px"> Hello Light <Button>Click me</Button> </Box> </Theme> </Box> </Theme> </Box> </Box> ) } ``` ### [Portalled]() Use the `asChild` prop to force the appearance of portalled elements like the popover and modal content. PreviewCode Click me Naruto Form Naruto is a Japanese manga series written and illustrated by Masashi Kishimoto. Click me ``` import { Button, Input, Text, Theme } from "@chakra-ui/react" import { PopoverArrow, PopoverBody, PopoverContent, PopoverRoot, PopoverTitle, PopoverTrigger, } from "@/components/ui/popover" const Demo = () => { return ( <PopoverRoot> <PopoverTrigger asChild> <Button size="sm" variant="outline"> Click me </Button> </PopoverTrigger> <PopoverContent asChild> <Theme hasBackground={false} appearance="dark" colorPalette="teal"> <PopoverArrow /> <PopoverBody spaceY="4"> <PopoverTitle fontWeight="medium">Naruto Form</PopoverTitle> <Text> Naruto is a Japanese manga series written and illustrated by Masashi Kishimoto. </Text> <Input placeholder="Search" /> <Button>Click me</Button> </PopoverBody> </Theme> </PopoverContent> </PopoverRoot> ) } ``` ### [Page Specific Color Mode]() To lock a page to a specific color mode (light or dark), wrap the entire page with the `Theme` component. You can also combine it with the `ColorModeProvider` if you use the `useColorMode` hook. ``` import { ColorModeProvider } from "@/components/ui/color-mode" import { Theme } from "@chakra-ui/react" export const ForcedColorMode = ({ children }) => { return ( <ColorModeProvider forcedTheme="dark"> <Theme appearance="dark">{/* Rest of the page */}</Theme> </ColorModeProvider> ) } ``` [Previous \ Stack](https://www.chakra-ui.com/docs/components/stack) [Next \ Blockquote](https://www.chakra-ui.com/docs/components/blockquote)
https://www.chakra-ui.com/docs/components/blockquote
1. Typography 2. Blockquote # Blockquote Used to quote text content from an external source [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/blockquote)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Fcomponents-blockquote--basic)[Recipe](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/theme/recipes/blockquote.ts) PreviewCode > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. ``` import { Blockquote } from "@/components/ui/blockquote" const Demo = () => { return ( <Blockquote> If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. </Blockquote> ) } ``` ## [Setup]() If you don't already have the snippet, run the following command to add the `blockquote` snippet ``` npx @chakra-ui/cli snippet add blockquote ``` The snippet includes a closed component composition for the `Blockquote` component. ``` import { Blockquote } from "@/components/ui/blockquote" ``` ``` <Blockquote dash cite="Uzumaki Naruto" citeUrl="#" /> ``` ## [Examples]() ### [With Cite]() Use the `cite` prop to provide the source of the blockquote. This will be displayed below the blockquote. PreviewCode > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. — Uzumaki Naruto ``` import { Blockquote } from "@/components/ui/blockquote" const Demo = () => { return ( <Blockquote showDash cite="Uzumaki Naruto"> If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. </Blockquote> ) } ``` ### [Colors]() Use the `colorPalette` prop to change the color of the blockquote. PreviewCode gray > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. — Uzumaki Naruto red > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. — Uzumaki Naruto green > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. — Uzumaki Naruto blue > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. — Uzumaki Naruto teal > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. — Uzumaki Naruto pink > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. — Uzumaki Naruto purple > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. — Uzumaki Naruto cyan > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. — Uzumaki Naruto orange > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. — Uzumaki Naruto yellow > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. — Uzumaki Naruto ``` import { Stack, Text } from "@chakra-ui/react" import { colorPalettes } from "compositions/lib/color-palettes" import { Blockquote } from "@/components/ui/blockquote" const Demo = () => { return ( <Stack gap="5" align="flex-start"> {colorPalettes.map((colorPalette) => ( <Stack align="center" key={colorPalette} direction="row" gap="10" px="4" width="full" > <Text minW="8ch">{colorPalette}</Text> <Blockquote showDash colorPalette={colorPalette} cite="Uzumaki Naruto" > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. </Blockquote> </Stack> ))} </Stack> ) } ``` ### [Variants]() Use the `variant` prop to change the visual style of the blockquote. Values can be either `subtle`, `solid`, `plain`. PreviewCode > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. ``` import { Stack } from "@chakra-ui/react" import { Blockquote } from "@/components/ui/blockquote" const Demo = () => { return ( <Stack gap="8"> <Blockquote variant="subtle"> If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. </Blockquote> <Blockquote variant="solid"> If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. </Blockquote> </Stack> ) } ``` ### [Icon]() Use the `showIcon` prop to show an icon on the blockquote. The default icon is a double quote. PreviewCode > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. — Uzumaki Naruto ``` import { Float } from "@chakra-ui/react" import { Blockquote, BlockquoteIcon } from "@/components/ui/blockquote" const Demo = () => { return ( <Blockquote variant="plain" colorPalette="teal" showDash icon={ <Float placement="top-start" offsetY="2"> <BlockquoteIcon /> </Float> } cite="Uzumaki Naruto" > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. </Blockquote> ) } ``` ### [Justify]() Use the `justify` prop to change the alignment of the blockquote. Values can be either `start`, `center`, `end`. PreviewCode start > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. — Naruto Uzumaki center > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. — Naruto Uzumaki end > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. — Naruto Uzumaki ``` import { For, HStack, Stack, Text } from "@chakra-ui/react" import { Blockquote } from "@/components/ui/blockquote" const Demo = () => { return ( <Stack gap="20"> <For each={["start", "center", "end"]}> {(justify) => ( <HStack key={justify} maxW="xl"> <Text color="fg.muted" minW="6rem"> {justify} </Text> <Blockquote variant="plain" justify={justify} showDash cite="Naruto Uzumaki" > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. </Blockquote> </HStack> )} </For> </Stack> ) } ``` ### [Custom Icon]() Use the `icon` prop to change the icon of the blockquote. PreviewCode > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. Uzumaki Naruto ``` import { Circle, Float } from "@chakra-ui/react" import { Blockquote } from "@/components/ui/blockquote" import { LuQuote } from "react-icons/lu" const Demo = () => { return ( <Blockquote cite="Uzumaki Naruto" colorPalette="blue" ps="8" icon={ <Float placement="middle-start"> <Circle bg="blue.600" size="8" color="white"> <LuQuote /> </Circle> </Float> } > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. </Blockquote> ) } ``` ### [With Avatar]() Here's an example of how to use the `Blockquote` with an avatar and float components to create a stunning testimonial component. PreviewCode > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. EJ![](https://i.pravatar.cc/150?u=re) Emily Jones ``` import { Float, HStack, Span } from "@chakra-ui/react" import { Avatar } from "@/components/ui/avatar" import { Blockquote, BlockquoteIcon } from "@/components/ui/blockquote" const Demo = () => { return ( <Blockquote bg="bg.subtle" padding="8" icon={ <Float placement="bottom-end" offset="10"> <BlockquoteIcon opacity="0.4" boxSize="10" rotate="180deg" /> </Float> } cite={ <HStack mt="2" gap="3"> <Avatar size="sm" name="Emily Jones" src="https://i.pravatar.cc/150?u=re" /> <Span fontWeight="medium">Emily Jones</Span> </HStack> } > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. </Blockquote> ) } ``` ### [Without Snippet]() If you don't want to use the snippet, you can use the `Blockquote` component from the `@chakra-ui/react` package. PreviewCode > If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. ``` import { Blockquote } from "@chakra-ui/react" const Demo = () => { return ( <Blockquote.Root> <Blockquote.Content> If anyone thinks he is something when he is nothing, he deceives himself. Each one should test his own actions. Then he can take pride in himself, without comparing himself to anyone else. </Blockquote.Content> </Blockquote.Root> ) } ``` ## [Props]() ### [Root]() PropDefaultType`colorPalette``'gray'` `'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink' | 'accent'` The color palette of the component `justify``'start'` `'start' | 'center' | 'end'` The justify of the component `variant``'subtle'` `'subtle' | 'solid'` The variant of the component [Previous \ Theme](https://www.chakra-ui.com/docs/components/theme) [Next \ Code](https://www.chakra-ui.com/docs/components/code)
https://www.chakra-ui.com/docs/components/link
1. Typography 2. Link # Link Used to provide accessible navigation [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/link)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Ftypography-link--basic)[Recipe](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/theme/recipes/link.ts) PreviewCode [Visit Chakra UI]() ``` import { Link } from "@chakra-ui/react" const Demo = () => { return <Link href="#">Visit Chakra UI</Link> } ``` ## [Usage]() ``` import { Link } from "@chakra-ui/react" ``` ``` <Link href="...">Click here</Link> ``` ## [Examples]() ### [Variants]() Use the `variant` prop to change the appearance of the `Link` component PreviewCode [Link (Underline)]()[Link (Plain)]() ``` import { Link, Stack } from "@chakra-ui/react" const Demo = () => { return ( <Stack> <Link variant="underline" href="#"> Link (Underline) </Link> <Link variant="plain" href="#"> Link (Plain) </Link> </Stack> ) } ``` ### [Within Text]() Use `Link` within a text to create a hyperlink PreviewCode Visit the [Chakra UI](https://chakra-ui.com) website ``` import { Link, Text } from "@chakra-ui/react" const Demo = () => { return ( <Text> Visit the{" "} <Link variant="underline" href="https://chakra-ui.com" colorPalette="teal" > Chakra UI </Link>{" "} website </Text> ) } ``` ### [External]() Add an external link icon to the `Link` component PreviewCode [Visit Chakra UI]() ``` import { Link } from "@chakra-ui/react" import { LuExternalLink } from "react-icons/lu" const Demo = () => { return ( <Link href="#"> Visit Chakra UI <LuExternalLink /> </Link> ) } ``` ### [Routing Library]() Use the `asChild` prop to compose `Link` with framework links like (Next.js) ``` import { Link as ChakraLink } from "@chakra-ui/react" import NextLink from "next/link" const Demo = () => { return ( <ChakraLink asChild> <NextLink href="/about">Click here</NextLink> </ChakraLink> ) } ``` ## [Props]() PropDefaultType`colorPalette``'gray'` `'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink' | 'accent'` The color palette of the component `variant``'plain'` `'underline' | 'plain'` The variant of the component [Previous \ Kbd](https://www.chakra-ui.com/docs/components/kbd) [Next \ Link Overlay](https://www.chakra-ui.com/docs/components/link-overlay)
https://www.chakra-ui.com/docs/components/highlight
1. Typography 2. Highlight # Highlight Used to highlight substrings of a text. [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/highlight)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Ftypography-highlight--basic)[Recipe](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/theme/recipes/highlight.ts)[Ark](https://ark-ui.com/react/docs/utilities/highlight) PreviewCode With the Highlight component, you can spotlight words. ``` import { Highlight } from "@chakra-ui/react" const Demo = () => { return ( <Highlight query="spotlight" styles={{ px: "0.5", bg: "orange.subtle", color: "orange.fg" }} > With the Highlight component, you can spotlight words. </Highlight> ) } ``` ## [Usage]() ``` import { Highlight } from "@chakra-ui/react" ``` ``` <Highlight query="Hello">Hello World</Highlight> ``` ## [Examples]() ### [Multiple]() Pass an array of strings to the `query` prop to highlight multiple substrings. PreviewCode ## With the Highlight component, you can spotlight, emphasize and accentuate words. ``` import { Heading, Highlight } from "@chakra-ui/react" const Demo = () => { return ( <Heading lineHeight="tall"> <Highlight query={["spotlight", "emphasize", "Accentuate"]} styles={{ px: "0.5", bg: "teal.muted" }} > With the Highlight component, you can spotlight, emphasize and accentuate words. </Highlight> </Heading> ) } ``` ### [Custom Style]() Use the `styles` prop to customize the style of the highlighted text. PreviewCode With the Highlight component, you can spotlight words. ``` import { Highlight } from "@chakra-ui/react" const Demo = () => { return ( <Highlight query="component" styles={{ fontWeight: "semibold" }}> With the Highlight component, you can spotlight words. </Highlight> ) } ``` ### [Search Query]() Use the highlight component to highlight search query results. PreviewCode Search result for: spot Spotlight bulb Spot cleaner Spot ceiling ``` import { Highlight, Stack, Text } from "@chakra-ui/react" const query = "spot" const results = ["Spotlight bulb", "Spot cleaner", "Spot ceiling"] const Demo = () => { return ( <Stack gap="6"> <Text>Search result for: spot</Text> <Stack gap="1"> {results.map((item) => ( <p key={item}> <Highlight ignoreCase query={query} styles={{ fontWeight: "semibold" }} > {item} </Highlight> </p> ))} </Stack> </Stack> ) } ``` ### [With Squiggle]() Here's an example of how to render a custom squiggle image around the highlighted text. Useful for a more fancy effect. PreviewCode ## Endless scale, powered by real humans.![](https://uploads-ssl.webflow.com/5fac11c3554384e2baf6481c/61c4dc7572d22f05ba26fd34_hero-underline.svg) ``` "use client" import { Heading, Mark, useHighlight } from "@chakra-ui/react" import { Fragment } from "react" const Demo = () => { const chunks = useHighlight({ text: "Endless scale, powered by real humans.", query: ["endless", "real humans."], }) return ( <Heading size="2xl" maxW="20ch"> {chunks.map((chunk, index) => { return chunk.match ? ( <Mark key={index} css={{ fontStyle: "italic", color: "red.500", position: "relative", }} > {chunk.text} <img style={{ position: "absolute", left: 0 }} src="https://uploads-ssl.webflow.com/5fac11c3554384e2baf6481c/61c4dc7572d22f05ba26fd34_hero-underline.svg" loading="lazy" alt="" /> </Mark> ) : ( <Fragment key={index}>{chunk.text}</Fragment> ) })} </Heading> ) } ``` ## [Props]() PropDefaultType`query`* `string | string[]` The query to highlight in the text `text`* `string` The text to highlight `ignoreCase` `boolean` Whether to ignore case while matching `matchAll` `boolean` Whether to match multiple instances of the query `styles` `SystemStyleObject` [Previous \ Heading](https://www.chakra-ui.com/docs/components/heading) [Next \ Kbd](https://www.chakra-ui.com/docs/components/kbd)
https://www.chakra-ui.com/docs/components/kbd
1. Typography 2. Kbd # Kbd Used to show key combinations for an action [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/kbd)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Fcomponents-kbd--basic)[Recipe](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/theme/recipes/kbd.ts) PreviewCode `Shift + Tab` ``` import { Kbd } from "@chakra-ui/react" const Demo = () => { return <Kbd>Shift + Tab</Kbd> } ``` ## [Usage]() ``` import { Kbd } from "@chakra-ui/react" ``` ``` <Kbd>F12</Kbd> ``` ## [Examples]() ### [Combinations]() Render `Kbd` to showcase key combinations PreviewCode `ctrl`+`shift`+`del` ``` import { HStack, Kbd } from "@chakra-ui/react" const Demo = () => { return ( <HStack gap="1"> <Kbd>ctrl</Kbd>+<Kbd>shift</Kbd>+<Kbd>del</Kbd> </HStack> ) } ``` ### [Function Keys]() Here's an example of using `Kbd` to showcase function keys PreviewCode `⌘⌥⇧⌃` ``` import { HStack, Kbd } from "@chakra-ui/react" const Demo = () => { return ( <HStack> <Kbd>⌘</Kbd> <Kbd>⌥</Kbd> <Kbd>⇧</Kbd> <Kbd>⌃</Kbd> </HStack> ) } ``` ### [Variants]() Use the `variant` prop to change the appearance of the `Kbd` component PreviewCode `Shift + TabShift + TabShift + TabShift + Tab` ``` import { HStack, Kbd } from "@chakra-ui/react" const Demo = () => { return ( <HStack gap="4"> <Kbd variant="raised">Shift + Tab</Kbd> <Kbd variant="outline">Shift + Tab</Kbd> <Kbd variant="subtle">Shift + Tab</Kbd> <Kbd variant="plain">Shift + Tab</Kbd> </HStack> ) } ``` ### [Sizes]() Use the `size` prop to change the size of the `Kbd` component PreviewCode `Shift + TabShift + TabShift + Tab` ``` import { HStack, Kbd } from "@chakra-ui/react" const Demo = () => { return ( <HStack gap="4"> <Kbd size="sm">Shift + Tab</Kbd> <Kbd size="md">Shift + Tab</Kbd> <Kbd size="lg">Shift + Tab</Kbd> </HStack> ) } ``` ### [Within Text]() Use `Kbd` within text to highlight key combinations PreviewCode Press `F12` to open DevTools ``` import { Kbd, Text } from "@chakra-ui/react" const Demo = () => { return ( <Text> Press <Kbd>F12</Kbd> to open DevTools </Text> ) } ``` ## [Props]() PropDefaultType`colorPalette``'gray'` `'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink' | 'accent'` The color palette of the component `variant``'raised'` `'raised' | 'outline' | 'subtle' | 'plain'` The variant of the component `size``'md'` `'sm' | 'md' | 'lg'` The size of the component [Previous \ Highlight](https://www.chakra-ui.com/docs/components/highlight) [Next \ Link](https://www.chakra-ui.com/docs/components/link)
https://www.chakra-ui.com/docs/components/em
1. Typography 2. Em # Em Used to mark text for emphasis. PreviewCode The *design system* is a collection of UI elements ``` import { Em, Text } from "@chakra-ui/react" const Demo = () => { return ( <Text> The <Em>design system</Em> is a collection of UI elements </Text> ) } ``` ## [Usage]() ``` import { Em } from "@chakra-ui/react" ``` ``` <Text> The <Em>design system</Em> is a collection of UI elements </Text> ``` [Previous \ Code](https://www.chakra-ui.com/docs/components/code) [Next \ Heading](https://www.chakra-ui.com/docs/components/heading)
https://www.chakra-ui.com/docs/components/list
1. Typography 2. List # List Used to display a list of items [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/list)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Fcomponents-list--basic)[Recipe](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/theme/recipes/list.ts) PreviewCode - Lorem ipsum dolor sit amet, consectetur adipisicing elit - Assumenda, quia temporibus eveniet a libero incidunt suscipit - Quidem, ipsam illum quis sed voluptatum quae eum fugit earum ``` import { List } from "@chakra-ui/react" export const ListBasic = () => ( <List.Root> <List.Item> Lorem ipsum dolor sit amet, consectetur adipisicing elit </List.Item> <List.Item> Assumenda, quia temporibus eveniet a libero incidunt suscipit </List.Item> <List.Item> Quidem, ipsam illum quis sed voluptatum quae eum fugit earum </List.Item> </List.Root> ) ``` ## [Usage]() ``` import { List } from "@chakra-ui/react" ``` ``` <List.Root> <List.Item>Item 1</List.Item> <List.Item>Item 2</List.Item> </List.Root> ``` ## [Examples]() ### [Ordered]() Pass the `as="ol"` prop to create an ordered list PreviewCode 1. Lorem ipsum dolor sit amet, consectetur adipisicing elit 2. Assumenda, quia temporibus eveniet a libero incidunt suscipit 3. Quidem, ipsam illum quis sed voluptatum quae eum fugit earum ``` import { List } from "@chakra-ui/react" const Demo = () => { return ( <List.Root as="ol"> <List.Item> Lorem ipsum dolor sit amet, consectetur adipisicing elit </List.Item> <List.Item> Assumenda, quia temporibus eveniet a libero incidunt suscipit </List.Item> <List.Item> Quidem, ipsam illum quis sed voluptatum quae eum fugit earum </List.Item> </List.Root> ) } ``` ### [Icon]() Use the `List.Indicator` component to add an icon to the list PreviewCode - Lorem ipsum dolor sit amet, consectetur adipisicing elit - Assumenda, quia temporibus eveniet a libero incidunt suscipit - Quidem, ipsam illum quis sed voluptatum quae eum fugit earum ``` import { List } from "@chakra-ui/react" import { LuCheckCircle, LuCircleDashed } from "react-icons/lu" const Demo = () => { return ( <List.Root gap="2" variant="plain" align="center"> <List.Item> <List.Indicator asChild color="green.500"> <LuCheckCircle /> </List.Indicator> Lorem ipsum dolor sit amet, consectetur adipisicing elit </List.Item> <List.Item> <List.Indicator asChild color="green.500"> <LuCheckCircle /> </List.Indicator> Assumenda, quia temporibus eveniet a libero incidunt suscipit </List.Item> <List.Item> <List.Indicator asChild color="green.500"> <LuCircleDashed /> </List.Indicator> Quidem, ipsam illum quis sed voluptatum quae eum fugit earum </List.Item> </List.Root> ) } ``` ### [Nested]() Here's an example of a nested list PreviewCode - First order item - First order item - First order item with list - Nested item - Nested item - Nested item - First order item ``` import { List } from "@chakra-ui/react" const Demo = () => { return ( <List.Root> <List.Item>First order item</List.Item> <List.Item>First order item</List.Item> <List.Item> First order item with list <List.Root ps="5"> <List.Item>Nested item</List.Item> <List.Item>Nested item</List.Item> <List.Item>Nested item</List.Item> </List.Root> </List.Item> <List.Item>First order item</List.Item> </List.Root> ) } ``` ### [Marker Style]() Use the `_marker` prop to style the marker of the list PreviewCode 1. Your failure to comply with any provision of these Terms of Service; 2. Your use of the Services, including but not limited to economic, physical, emotional, psychological or privacy related considerations; and 3. Your actions to knowingly affect the Services via any bloatware, malware, computer virus, worm, Trojan horse, spyware, adware, crimeware, scareware, rootkit or any other program installed in a way that executable code of any program is scheduled to utilize or utilizes processor cycles during periods of time when such program is not directly or indirectly being used. ``` import { List } from "@chakra-ui/react" const items = [ "Your failure to comply with any provision of these Terms of Service;", "Your use of the Services, including but not limited to economic, physical, emotional, psychological or privacy related considerations; and", "Your actions to knowingly affect the Services via any bloatware, malware, computer virus, worm, Trojan horse, spyware, adware, crimeware, scareware, rootkit or any other program installed in a way that executable code of any program is scheduled to utilize or utilizes processor cycles during periods of time when such program is not directly or indirectly being used.", ] const Demo = () => { return ( <List.Root as="ol" listStyle="decimal"> {items.map((item, index) => ( <List.Item key={index} _marker={{ color: "inherit" }}> {item} </List.Item> ))} </List.Root> ) } ``` ## [Props]() PropDefaultType`colorPalette``'gray'` `'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink' | 'accent'` The color palette of the component `variant``'marker'` `'marker' | 'plain'` The variant of the component `align` `'center' | 'start' | 'end'` The align of the component [Previous \ Link Overlay](https://www.chakra-ui.com/docs/components/link-overlay) [Next \ Mark](https://www.chakra-ui.com/docs/components/mark)
https://www.chakra-ui.com/docs/components/mark
1. Typography 2. Mark # Mark Used to mark text for emphasis. PreviewCode The design system is a collection of UI elements ``` import { Mark, Text } from "@chakra-ui/react" const Demo = () => { return ( <Text> The <Mark variant="subtle">design system</Mark> is a collection of UI elements </Text> ) } ``` ## [Usage]() ``` import { Mark } from "@chakra-ui/react" ``` ``` <Text> The <Mark>design system</Mark> is a collection of UI elements </Text> ``` ## [Examples]() ### [Variants]() Use the `variant` prop to change the color of the mark. The design system is a collection of UI elements The design system is a collection of UI elements The design system is a collection of UI elements The design system is a collection of UI elements ``` import { For, Mark, Stack, Text } from "@chakra-ui/react" const Demo = () => { return ( <Stack gap="6"> <For each={["subtle", "solid", "text", "plain"]}> {(variant) => ( <Text key={variant}> The <Mark variant={variant}>design system</Mark> is a collection of UI elements </Text> )} </For> </Stack> ) } ``` ## [Props]() [Previous \ List](https://www.chakra-ui.com/docs/components/list) [Next \ Prose](https://www.chakra-ui.com/docs/components/prose)
https://www.chakra-ui.com/docs/components/prose
1. Typography 2. Prose # Prose Used to style remote HTML content PreviewCode # Title Heading 1 ## Title Heading 2 ### Title Heading 3 #### Title Heading 4 #### Title Heading 4 `testing` Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi at dolor nec ex rutrum semper. Praesent ultricies purus eget lectus tristique egestas ac in lacus. Nulla eleifend lorem risus, sit amet dictum nisi gravida eget. Suspendisse odio sem, scelerisque congue luctus nec, scelerisque ultrices orci. Praesent tincidunt, risus ut commodo cursus, ligula orci tristique justo, vitae sollicitudin lacus risus dictum orci. Press `Ctrl` + `C` to copy Vivamus vel enim at lorem ultricies faucibus. Cras vitae ipsum ut quam varius dignissim a ac tellus. Aliquam maximus mauris eget tincidunt interdum. Fusce vitae massa non risus congue tincidunt. Pellentesque maximus elit quis eros lobortis dictum. * * * Fusce placerat ipsum vel sollicitudin imperdiet. Morbi vulputate non diam at consequat. Donec vitae sem eu arcu auctor scelerisque vel in turpis. Pellentesque dapibus justo dui, quis egestas sapien porttitor in. ``` import { Prose } from "@/components/ui/prose" // Used for syntax highlighting const html = String.raw const content = html` <h1>Title Heading 1</h1> <h2>Title Heading 2</h2> <h3>Title Heading 3</h3> <h4>Title Heading 4</h4> <h4>Title Heading 4 <code>testing</code></h4> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi at dolor nec ex rutrum semper. Praesent ultricies purus eget lectus tristique egestas ac in lacus. Nulla eleifend lorem risus, sit amet dictum nisi gravida eget. Suspendisse odio sem, scelerisque congue luctus nec, scelerisque ultrices orci. Praesent tincidunt, risus ut commodo cursus, ligula orci tristique justo, vitae sollicitudin lacus risus dictum orci. Press <kbd>Ctrl</kbd> + <kbd>C</kbd> to copy </p> <p> Vivamus vel enim at lorem ultricies faucibus. Cras vitae ipsum ut quam varius dignissim a ac tellus. Aliquam maximus mauris eget tincidunt interdum. Fusce vitae massa non risus congue tincidunt. Pellentesque maximus elit quis eros lobortis dictum. </p> <hr /> <p> Fusce placerat ipsum vel sollicitudin imperdiet. Morbi vulputate non diam at consequat. Donec vitae sem eu arcu auctor scelerisque vel in turpis. Pellentesque dapibus justo dui, quis egestas sapien porttitor in. </p> ` const Demo = () => { return <Prose dangerouslySetInnerHTML={{ __html: content }} /> } ``` ## [Setup]() If you don't already have the snippet, run the following command to add the `prose` snippet ``` npx @chakra-ui/cli snippet add prose ``` ## [Usage]() ``` import { Prose } from "@/components/ui/prose" ``` ``` <Prose> <div dangerouslySetInnerHTML={{ __html: "..." }} /> </Prose> ``` ## [Examples]() ### [Sizes]() Use the `size` prop to change the size of the `Prose` component PreviewCode size: md # Title Heading 1 ## Title Heading 2 ### Title Heading 3 #### Title Heading 4 #### Title Heading 4 `testing` Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi at dolor nec ex rutrum semper. Praesent ultricies purus eget lectus tristique egestas ac in lacus. Nulla eleifend lorem risus, sit amet dictum nisi gravida eget. Suspendisse odio sem, scelerisque congue luctus nec, scelerisque ultrices orci. Praesent tincidunt, risus ut commodo cursus, ligula orci tristique justo, vitae sollicitudin lacus risus dictum orci. Press `Ctrl` +`C` to copy size: lg # Title Heading 1 ## Title Heading 2 ### Title Heading 3 #### Title Heading 4 #### Title Heading 4 `testing` Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi at dolor nec ex rutrum semper. Praesent ultricies purus eget lectus tristique egestas ac in lacus. Nulla eleifend lorem risus, sit amet dictum nisi gravida eget. Suspendisse odio sem, scelerisque congue luctus nec, scelerisque ultrices orci. Praesent tincidunt, risus ut commodo cursus, ligula orci tristique justo, vitae sollicitudin lacus risus dictum orci. Press `Ctrl` +`C` to copy ``` import { For, Stack, Text } from "@chakra-ui/react" import { Prose } from "@/components/ui/prose" const Demo = () => { return ( <Stack gap="10"> <For each={["md", "lg"]}> {(size) => ( <Stack key={size}> <Text>size: {size}</Text> <Prose size={size}> <h1>Title Heading 1</h1> <h2>Title Heading 2</h2> <h3>Title Heading 3</h3> <h4>Title Heading 4</h4> <h4> Title Heading 4 <code>testing</code> </h4> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi at dolor nec ex rutrum semper. Praesent ultricies purus eget lectus tristique egestas ac in lacus. Nulla eleifend lorem risus, sit amet dictum nisi gravida eget. Suspendisse odio sem, scelerisque congue luctus nec, scelerisque ultrices orci. Praesent tincidunt, risus ut commodo cursus, ligula orci tristique justo, vitae sollicitudin lacus risus dictum orci. Press <kbd>Ctrl</kbd> +<kbd>C</kbd> to copy </p> </Prose> </Stack> )} </For> </Stack> ) } ``` ### [Blockquote]() Blockquote elements are styled to match the design language of the `Blockquote` component. PreviewCode ### Blockquotes > This is a good looking blockquote! And it can span into multiple lines: > Fusce placerat ipsum vel sollicitudin imperdiet. Morbi vulputate non diam at consequat. Donec vitae sem eu arcu auctor scelerisque vel in turpis. Pellentesque dapibus justo dui, quis egestas sapien porttitor in. There's also **strong**, **b**, *em* support as well! But, let's display some code! ``` import { Prose } from "@/components/ui/prose" // Used for syntax highlighting const html = String.raw const content = html` <h3>Blockquotes</h3> <blockquote>This is a good looking blockquote!</blockquote> <p>And it can span into multiple lines:</p> <blockquote> Fusce placerat ipsum vel sollicitudin imperdiet. Morbi vulputate non diam at consequat. Donec vitae sem eu arcu auctor scelerisque vel in turpis. Pellentesque dapibus justo dui, quis egestas sapien porttitor in. </blockquote> <p> There&apos;s also <strong>strong</strong>, <b>b</b>, <em>em</em> support as well! But, let&apos;s display some code! </p> ` const Demo = () => { return <Prose dangerouslySetInnerHTML={{ __html: content }} /> } ``` ### [List]() List elements are styled to match the design language of the `List` component. PreviewCode ### Lists Let's look at some unordered lists. Things to buy: - Milk - Eggs - Bread - Chakra UI Pro license And some ordered lists. Things to do: 1. Pay the bills 2. Walk the dog 3. Take out trash ``` import { Prose } from "@/components/ui/prose" // Used for syntax highlighting const html = String.raw const content = html` <h3>Lists</h3> <p>Let's look at some unordered lists. Things to buy:</p> <ul> <li>Milk</li> <li>Eggs</li> <li>Bread</li> <li>Chakra UI Pro license</li> </ul> <p>And some ordered lists. Things to do:</p> <ol> <li>Pay the bills</li> <li>Walk the dog</li> <li>Take out trash</li> </ol> ` const Demo = () => { return <Prose dangerouslySetInnerHTML={{ __html: content }} /> } ``` ### [React Markdown]() Here's an example of using the `react-markdown` library to render markdown content. PreviewCode ## Heading Based on your Chakra package. So [click here](http://chakra-ui.com) to confirm your plan. - first item - second item - second item - second item [title](http://chakra-ui.com) ``` import { Prose } from "@/components/ui/prose" import Markdown from "react-markdown" const Demo = () => { return ( <Prose mx="auto"> <Markdown> {` ## Heading Based on your Chakra package. So [click here](http://chakra-ui.com) to confirm your plan. - first item - second item - second item - second item [title](http://chakra-ui.com) `} </Markdown> </Prose> ) } ``` ### [Table]() The table elements are styled to match the design language of the `Table` component. PreviewCode ### Tables Name Role GitHub Profile Segun Creator segunadebayo Chris Ark Wizard grizzlycodes Abraham Trouble maker anubra266 Esther Developer Advocate estheragbaje ``` import { Prose } from "@/components/ui/prose" // Used for syntax highlighting const html = String.raw const content = html` <h3>Tables</h3> <table> <thead> <tr> <th>Name</th> <th>Role</th> <th>GitHub Profile</th> </tr> </thead> <tbody> <tr> <td>Segun</td> <td>Creator</td> <td>segunadebayo</td> </tr> <tr> <td>Chris</td> <td>Ark Wizard</td> <td>grizzlycodes</td> </tr> <tr> <td>Abraham</td> <td>Trouble maker</td> <td>anubra266</td> </tr> <tr> <td>Esther</td> <td>Developer Advocate</td> <td>estheragbaje</td> </tr> </tbody> </table> ` const Demo = () => { return <Prose dangerouslySetInnerHTML={{ __html: content }} /> } ``` [Previous \ Mark](https://www.chakra-ui.com/docs/components/mark) [Next \ Text](https://www.chakra-ui.com/docs/components/text)
https://www.chakra-ui.com/docs/components/heading
1. Typography 2. Heading # Heading Used to render semantic HTML heading elements. PreviewCode ## The quick brown fox jumps over the lazy dog ``` import { Heading } from "@chakra-ui/react" const Demo = () => { return <Heading>The quick brown fox jumps over the lazy dog</Heading> } ``` ## [Usage]() ``` import { Heading } from "@chakra-ui/react" ``` ``` <Heading>I'm a Heading</Heading> ``` ## [Examples]() ### [Sizes]() Use the `size` prop to change the size of the heading component. PreviewCode ## Heading (sm) ## Heading (md) ## Heading (lg) ## Heading (xl) ## Heading (2xl) ## Heading (3xl) ## Heading (4xl) ## Heading (5xl) ## Heading (6xl) ``` import { Heading, Stack } from "@chakra-ui/react" const Demo = () => { return ( <Stack gap="2" align="flex-start"> <Heading size="sm">Heading (sm)</Heading> <Heading size="md">Heading (md)</Heading> <Heading size="lg">Heading (lg)</Heading> <Heading size="xl">Heading (xl)</Heading> <Heading size="2xl">Heading (2xl)</Heading> <Heading size="3xl">Heading (3xl)</Heading> <Heading size="4xl">Heading (4xl)</Heading> <Heading size="5xl">Heading (5xl)</Heading> <Heading size="6xl">Heading (6xl)</Heading> </Stack> ) } ``` ### [Highlight]() Compose the `Heading` component with the `Highlight` component to highlight text. PreviewCode ## Create accessible React apps with speed Chakra UI is a simple, modular and accessible component library that gives you the building blocks you need. ``` import { Heading, Highlight, Stack, Text } from "@chakra-ui/react" const Demo = () => { return ( <Stack> <Heading size="3xl" letterSpacing="tight"> <Highlight query="with speed" styles={{ color: "teal.600" }}> Create accessible React apps with speed </Highlight> </Heading> <Text fontSize="md" color="fg.muted"> Chakra UI is a simple, modular and accessible component library that gives you the building blocks you need. </Text> </Stack> ) } ``` ### [As another element]() Use the `as` prop to render the heading as another HTML element. PreviewCode # Level 1 ## Level 2 ### Level 3 ``` import { Heading, Stack } from "@chakra-ui/react" const Demo = () => { return ( <Stack> <Heading as="h1">Level 1</Heading> <Heading as="h2">Level 2</Heading> <Heading as="h3">Level 3</Heading> </Stack> ) } ``` ### [Weights]() Use the `fontWeight` prop to change the weight of the heading component. PreviewCode ## Normal ## Medium ## Semibold ## Bold ``` import { Heading, Stack } from "@chakra-ui/react" const Demo = () => { return ( <Stack> <Heading fontWeight="normal">Normal</Heading> <Heading fontWeight="medium">Medium</Heading> <Heading fontWeight="semibold">Semibold</Heading> <Heading fontWeight="bold">Bold</Heading> </Stack> ) } ``` ### [Composition]() Use the `Heading` component to compose other components. PreviewCode ## Modern payments for Stores PayMe helps startups get paid by anyone, anywhere in the world Create account ``` import { Button, Heading, Stack, Text } from "@chakra-ui/react" import { LuArrowRight } from "react-icons/lu" const Demo = () => { return ( <Stack align="flex-start"> <Heading size="2xl">Modern payments for Stores</Heading> <Text mb="3" fontSize="md" color="fg.muted"> PayMe helps startups get paid by anyone, anywhere in the world </Text> <Button> Create account <LuArrowRight /> </Button> </Stack> ) } ``` ## [Props]() PropDefaultType`colorPalette``'gray'` `'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink' | 'accent'` The color palette of the component `size``'xl'` `'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl' | '3xl' | '4xl' | '5xl' | '6xl' | '7xl'` The size of the component [Previous \ Em](https://www.chakra-ui.com/docs/components/em) [Next \ Highlight](https://www.chakra-ui.com/docs/components/highlight)
https://www.chakra-ui.com/docs/components/link-overlay
13 days ago ## [Chakra V3 Workshop]() Catch up on whats been cooking at Chakra UI and explore some of the popular community resources. [Inner Link]()
https://www.chakra-ui.com/docs/components/action-bar
1. Components 2. Action Bar # Action Bar Used to display a bottom action bar with a set of actions [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/action-bar)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Fcomponents-action-bar--basic)[Recipe](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/theme/recipes/action-bar.ts) PreviewCode Show Action bar ``` "use client" import { ActionBarContent, ActionBarRoot, ActionBarSelectionTrigger, ActionBarSeparator, } from "@/components/ui/action-bar" import { Button } from "@/components/ui/button" import { Checkbox } from "@/components/ui/checkbox" import { useState } from "react" import { LuShare, LuTrash2 } from "react-icons/lu" const Demo = () => { const [checked, setChecked] = useState(false) return ( <> <Checkbox onCheckedChange={(e) => setChecked(!!e.checked)}> Show Action bar </Checkbox> <ActionBarRoot open={checked}> <ActionBarContent> <ActionBarSelectionTrigger>2 selected</ActionBarSelectionTrigger> <ActionBarSeparator /> <Button variant="outline" size="sm"> <LuTrash2 /> Delete </Button> <Button variant="outline" size="sm"> <LuShare /> Share </Button> </ActionBarContent> </ActionBarRoot> </> ) } ``` ## [Setup]() If you don't already have the snippet, run the following command to add the `action-bar` snippet ``` npx @chakra-ui/cli snippet add action-bar ``` The snippet includes a closed component composition based on the `Popover` component. ## [Usage]() The action bar is designed to be controlled by table or checkbox selections. It provides a set of actions that can be performed on the selected items. ``` import { ActionBarCloseTrigger, ActionBarContent, ActionBarRoot, ActionBarSelectionTrigger, ActionBarSeparator, } from "@/components/ui/action-bar" ``` ``` <ActionBarRoot> <ActionBarContent> <ActionBarCloseTrigger /> <ActionBarSelectionTrigger /> <ActionBarSeparator /> <Button /> </ActionBarContent> </ActionBarRoot> ``` ## [Examples]() ### [Close Trigger]() Render the `ActionBarCloseTrigger` to close the action bar, and pass the `onOpenChange` handler to control the visibility of the action bar. The `open` and `onOpenChange` props control the visibility of the action bar. PreviewCode Show Action bar ``` "use client" import { ActionBarCloseTrigger, ActionBarContent, ActionBarRoot, ActionBarSelectionTrigger, ActionBarSeparator, } from "@/components/ui/action-bar" import { Button } from "@/components/ui/button" import { Checkbox } from "@/components/ui/checkbox" import { useState } from "react" import { LuShare, LuTrash2 } from "react-icons/lu" const Demo = () => { const [checked, setChecked] = useState(false) return ( <> <Checkbox checked={checked} onCheckedChange={(e) => setChecked(!!e.checked)} > Show Action bar </Checkbox> <ActionBarRoot open={checked} onOpenChange={(e) => setChecked(e.open)} closeOnInteractOutside={false} > <ActionBarContent> <ActionBarSelectionTrigger>2 selected</ActionBarSelectionTrigger> <ActionBarSeparator /> <Button variant="outline" size="sm"> <LuTrash2 /> Delete </Button> <Button variant="outline" size="sm"> <LuShare /> Share </Button> <ActionBarCloseTrigger /> </ActionBarContent> </ActionBarRoot> </> ) } ``` ### [Within Dialog]() Here's an example of composing the `ActionBar` and the `Dialog` to perform a delete action on a set of selected items. Press the `Delete projects` button to open the dialog. PreviewCode Check to select projects ``` "use client" import { DialogHeader } from "@chakra-ui/react" import { ActionBarContent, ActionBarRoot, ActionBarSelectionTrigger, ActionBarSeparator, } from "@/components/ui/action-bar" import { Button } from "@/components/ui/button" import { Checkbox } from "@/components/ui/checkbox" import { DialogBody, DialogContent, DialogDescription, DialogFooter, DialogRoot, DialogTitle, DialogTrigger, } from "@/components/ui/dialog" import { useState } from "react" import { LuPlusSquare, LuTrash2 } from "react-icons/lu" const Demo = () => { const [checked, setChecked] = useState(false) return ( <> <Checkbox onCheckedChange={(e) => setChecked(!!e.checked)}> Check to select projects </Checkbox> <ActionBarRoot open={checked}> <ActionBarContent> <ActionBarSelectionTrigger>4 selected</ActionBarSelectionTrigger> <ActionBarSeparator /> <Button variant="outline" size="sm"> <LuPlusSquare /> Add to collection </Button> <DialogRoot placement="center"> <DialogTrigger asChild> <Button variant="surface" colorPalette="red" size="sm"> <LuTrash2 /> Delete projects </Button> </DialogTrigger> <DialogContent> <DialogHeader> <DialogTitle>Delete projects</DialogTitle> </DialogHeader> <DialogBody> <DialogDescription> Are you sure you want to delete 4 projects? </DialogDescription> </DialogBody> <DialogFooter> <Button variant="outline">Cancel</Button> <Button colorPalette="red">Delete</Button> </DialogFooter> </DialogContent> </DialogRoot> </ActionBarContent> </ActionBarRoot> </> ) } ``` ### [Without Snippet]() If you don't want to use the snippet, you can use the `ActionBar` component from the `@chakra-ui/react` package. PreviewCode Show Action bar ``` "use client" import { ActionBar, Button, Checkbox, Portal } from "@chakra-ui/react" import { useState } from "react" import { LuShare, LuTrash2 } from "react-icons/lu" const Demo = () => { const [checked, setChecked] = useState(false) return ( <> <Checkbox.Root onCheckedChange={(e) => setChecked(!!e.checked)}> <Checkbox.HiddenInput /> <Checkbox.Control /> <Checkbox.Label>Show Action bar</Checkbox.Label> </Checkbox.Root> <ActionBar.Root open={checked}> <Portal> <ActionBar.Positioner> <ActionBar.Content> <ActionBar.SelectionTrigger> 2 selected </ActionBar.SelectionTrigger> <ActionBar.Separator /> <Button variant="outline" size="sm"> <LuTrash2 /> Delete </Button> <Button variant="outline" size="sm"> <LuShare /> Share </Button> </ActionBar.Content> </ActionBar.Positioner> </Portal> </ActionBar.Root> </> ) } ``` ## [Props]() ### [Root]() PropDefaultType No props to display [Previous \ Accordion](https://www.chakra-ui.com/docs/components/accordion) [Next \ Alert](https://www.chakra-ui.com/docs/components/alert)
https://www.chakra-ui.com/docs/components/text
1. Typography 2. Text # Text Used to render text and paragraphs within an interface. [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/typography) PreviewCode Sphinx of black quartz, judge my vow. ``` import { Text } from "@chakra-ui/react" const Demo = () => { return <Text>Sphinx of black quartz, judge my vow.</Text> } ``` ## [Usage]() ``` import { Text } from "@chakra-ui/react" ``` ``` <Text>This is the text component</Text> ``` ## [Examples]() ### [Sizes]() Use the `fontSize` or `textStyle` prop to change the size of the text. PreviewCode Chakra Chakra Chakra Chakra Chakra Chakra Chakra Chakra Chakra Chakra Chakra ``` import { Stack, Text } from "@chakra-ui/react" const Demo = () => { return ( <Stack> <Text textStyle="xs">Chakra</Text> <Text textStyle="sm">Chakra</Text> <Text textStyle="md">Chakra</Text> <Text textStyle="lg">Chakra</Text> <Text textStyle="xl">Chakra</Text> <Text textStyle="2xl">Chakra</Text> <Text textStyle="3xl">Chakra</Text> <Text textStyle="4xl">Chakra</Text> <Text textStyle="5xl">Chakra</Text> <Text textStyle="6xl">Chakra</Text> <Text textStyle="7xl">Chakra</Text> </Stack> ) } ``` ### [Weights]() Use the `fontWeight` prop to change the weight of the text. PreviewCode Sphinx of black quartz, judge my vow. Sphinx of black quartz, judge my vow. Sphinx of black quartz, judge my vow. Sphinx of black quartz, judge my vow. Sphinx of black quartz, judge my vow. ``` import { Stack, Text } from "@chakra-ui/react" const Demo = () => { return ( <Stack> <Text fontWeight="light">Sphinx of black quartz, judge my vow.</Text> <Text fontWeight="normal">Sphinx of black quartz, judge my vow.</Text> <Text fontWeight="medium">Sphinx of black quartz, judge my vow.</Text> <Text fontWeight="semibold">Sphinx of black quartz, judge my vow.</Text> <Text fontWeight="bold">Sphinx of black quartz, judge my vow.</Text> </Stack> ) } ``` ### [Truncation]() Use the `truncate` prop to truncate the text after a single line. PreviewCode Lorem ipsum dolor sit amet, consectetur adipiscing elit. ``` import { Flex, Text } from "@chakra-ui/react" const Demo = () => { return ( <Flex maxW="300px"> <Text truncate> Lorem ipsum dolor sit amet, consectetur adipiscing elit. </Text> </Flex> ) } ``` ### [Line Clamp]() Use the `lineClamp` prop to truncate the text after a certain number of lines. PreviewCode Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ``` import { Flex, Text } from "@chakra-ui/react" const Demo = () => { return ( <Flex maxW="300px"> <Text lineClamp="2"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </Text> </Flex> ) } ``` [Previous \ Prose](https://www.chakra-ui.com/docs/components/prose) [Next \ Accordion](https://www.chakra-ui.com/docs/components/accordion)
https://www.chakra-ui.com/docs/components/alert
1. Components 2. Alert # Alert Used to communicate a state that affects a system, feature or page. [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/alert)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Fcomponents-alert--basic)[Recipe](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/theme/recipes/alert.ts) PreviewCode This is the alert title ``` import { Alert } from "@/components/ui/alert" const Demo = () => { return <Alert status="info" title="This is the alert title" /> } ``` ## [Setup]() If you don't already have the snippet, run the following command to add the `alert` snippet ``` npx @chakra-ui/cli snippet add alert ``` The snippet includes a closed component composition for the `Alert` component. ## [Usage]() ``` import { Alert } from "@/components/ui/alert" ``` ``` <Alert title="Alert Title" icon={<LuTerminal />}> This is the alert description </Alert> ``` ## [Examples]() ### [Description]() Use the `children` prop to provide additional context to the alert. This will be displayed below the alert message. PreviewCode Invalid Fields Your form has some errors. Please fix them and try again. ``` import { Alert } from "@/components/ui/alert" const Demo = () => { return ( <Alert status="error" title="Invalid Fields"> Your form has some errors. Please fix them and try again. </Alert> ) } ``` ### [Status]() Change the status of the alerts by passing the `status` prop. This affects the color scheme and icon used. Alert supports `error`, `success`, `warning`, and `info` statuses. PreviewCode There was an error processing your request Chakra is going live on August 30th. Get ready! Seems your account is about expire, upgrade now Data uploaded to the server. Fire on! ``` import { Stack } from "@chakra-ui/react" import { Alert } from "@/components/ui/alert" const Demo = () => { return ( <Stack gap="2" width="full"> <Alert status="error" title="There was an error processing your request" /> <Alert status="info" title="Chakra is going live on August 30th. Get ready!" /> <Alert status="warning" title="Seems your account is about expire, upgrade now" /> <Alert status="success" title="Data uploaded to the server. Fire on!" /> </Stack> ) } ``` ### [Variants]() Use the `variant` prop to change the visual style of the alert. Values can be either `subtle`, `solid`, `outline` PreviewCode Data uploaded to the server. Fire on! Data uploaded to the server. Fire on! Data uploaded to the server. Fire on! ``` import { Stack } from "@chakra-ui/react" import { Alert } from "@/components/ui/alert" const Demo = () => { return ( <Stack gap="3"> <Alert status="success" variant="subtle" title="Data uploaded to the server. Fire on!" /> <Alert status="success" variant="solid" title="Data uploaded to the server. Fire on!" /> <Alert status="success" variant="surface" title="Data uploaded to the server. Fire on!" /> </Stack> ) } ``` ### [Custom Icon]() Use the `icon` prop to pass a custom icon to the alert. This will override the default icon for the alert status. PreviewCode Submitting this form will delete your account ``` import { Alert } from "@/components/ui/alert" import { LuAlarmPlus } from "react-icons/lu" const Demo = () => { return ( <Alert icon={<LuAlarmPlus />} status="warning" title="Submitting this form will delete your account" /> ) } ``` ### [Without Snippet]() Here's an example of how to use the `Alert` without the snippet. PreviewCode This is the alert title ``` import { Alert } from "@chakra-ui/react" const Demo = () => { return ( <Alert.Root status="info"> <Alert.Indicator /> <Alert.Title>This is the alert title</Alert.Title> </Alert.Root> ) } ``` ### [Color Palette Override]() The default colorPalette is inferred from the `status` prop. To override the color palette, pass the `colorPalette` prop. PreviewCode This is an info alert but shown as teal ``` import { Alert } from "@/components/ui/alert" const Demo = () => { return ( <Alert status="info" title="This is an info alert but shown as teal" colorPalette="teal" /> ) } ``` ## [Props]() ### [Root]() PropDefaultType`colorPalette``'gray'` `'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink' | 'accent'` The color palette of the component `status``'info'` `'info' | 'warning' | 'success' | 'error' | 'neutral'` The status of the component `variant``'subtle'` `'subtle' | 'surface' | 'outline' | 'solid'` The variant of the component `size``'md'` `'sm' | 'md' | 'lg'` The size of the component [Previous \ Action Bar](https://www.chakra-ui.com/docs/components/action-bar) [Next \ Avatar](https://www.chakra-ui.com/docs/components/avatar)
https://www.chakra-ui.com/docs/components/badge
1. Components 2. Badge # Badge Used to highlight an item's status for quick recognition. [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/badge)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Fcomponents-badge--basic)[Recipe](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/theme/recipes/badge.ts) PreviewCode DefaultSuccessRemovedNew ``` import { Badge, Stack } from "@chakra-ui/react" const Demo = () => { return ( <Stack direction="row"> <Badge>Default</Badge> <Badge colorPalette="green">Success</Badge> <Badge colorPalette="red">Removed</Badge> <Badge colorPalette="purple">New</Badge> </Stack> ) } ``` ## [Usage]() ``` import { Badge } from "@chakra-ui/react" ``` ``` <Badge>Badge</Badge> ``` ## [Examples]() ### [Icon]() Render an icon within the badge directly PreviewCode NewNew ``` import { Badge, Stack } from "@chakra-ui/react" import { HiAtSymbol, HiStar } from "react-icons/hi" const Demo = () => { return ( <Stack align="flex-start"> <Badge variant="solid" colorPalette="blue"> <HiStar /> New </Badge> <Badge variant="solid" colorPalette="green"> New <HiAtSymbol /> </Badge> </Stack> ) } ``` ### [Variants]() Badges come in different variants PreviewCode OutlineSolidSubtleSurface ``` import { Badge, Stack } from "@chakra-ui/react" const Demo = () => { return ( <Stack direction="row"> <Badge variant="outline">Outline</Badge> <Badge variant="solid">Solid</Badge> <Badge variant="subtle">Subtle</Badge> <Badge variant="surface">Surface</Badge> </Stack> ) } ``` ### [Sizes]() Badges come in different sizes PreviewCode NewNewNewNew ``` import { Badge, HStack } from "@chakra-ui/react" const Demo = () => { return ( <HStack> <Badge size="xs">New</Badge> <Badge size="sm">New</Badge> <Badge size="md">New</Badge> <Badge size="lg">New</Badge> </HStack> ) } ``` ## [Props]() PropDefaultType`colorPalette``'gray'` `'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink' | 'accent'` The color palette of the component `variant``'subtle'` `'solid' | 'subtle' | 'outline' | 'surface' | 'plain'` The variant of the component `size``'sm'` `'xs' | 'sm' | 'md' | 'lg'` The size of the component [Previous \ Avatar](https://www.chakra-ui.com/docs/components/avatar) [Next \ Breadcrumb](https://www.chakra-ui.com/docs/components/breadcrumb)
https://www.chakra-ui.com/docs/components/avatar
1. Components 2. Avatar # Avatar Used to represent user profile picture or initials [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/avatar)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Fcomponents-avatar--basic)[Recipe](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/theme/recipes/avatar.ts)[Ark](https://ark-ui.com/react/docs/components/avatar) PreviewCode SA![](https://bit.ly/sage-adebayo) ``` import { Avatar } from "@/components/ui/avatar" const Demo = () => { return <Avatar name="Segun Adebayo" src="https://bit.ly/sage-adebayo" /> } ``` ## [Setup]() If you don't already have the snippet, run the following command to add the `avatar` snippet ``` npx @chakra-ui/cli snippet add avatar ``` The snippet includes a closed component composition for the `Avatar` and `AvatarGroup` components. ## [Usage]() ``` import { Avatar, AvatarGroup } from "@/components/ui/avatar" ``` ``` <AvatarGroup> <Avatar /> </AvatarGroup> ``` ## [Examples]() ### [Sizes]() Use the `size` prop to change the size of the avatar PreviewCode S![](https://bit.ly/sage-adebayo) S![](https://bit.ly/sage-adebayo) S![](https://bit.ly/sage-adebayo) S![](https://bit.ly/sage-adebayo) S![](https://bit.ly/sage-adebayo) S![](https://bit.ly/sage-adebayo) ``` import { HStack } from "@chakra-ui/react" import { Avatar } from "@/components/ui/avatar" const Demo = () => { return ( <HStack gap="3"> <Avatar size="xs" name="Sage" src="https://bit.ly/sage-adebayo" /> <Avatar size="sm" name="Sage" src="https://bit.ly/sage-adebayo" /> <Avatar size="md" name="Sage" src="https://bit.ly/sage-adebayo" /> <Avatar size="lg" name="Sage" src="https://bit.ly/sage-adebayo" /> <Avatar size="xl" name="Sage" src="https://bit.ly/sage-adebayo" /> <Avatar size="2xl" name="Sage" src="https://bit.ly/sage-adebayo" /> </HStack> ) } ``` ### [Variants]() Use the `variant` prop to change the variant of the avatar PreviewCode SA SA SA ``` import { HStack } from "@chakra-ui/react" import { Avatar } from "@/components/ui/avatar" const Demo = () => { return ( <HStack gap="3"> <Avatar variant="solid" name="Sage Adebayo" /> <Avatar variant="outline" name="Sage Adebayo" /> <Avatar variant="subtle" name="Sage Adebayo" /> </HStack> ) } ``` ### [Shape]() Use the `shape` prop to change the shape of the avatar, from `rounded` to `square` PreviewCode DA![](https://bit.ly/dan-abramov) SA![](https://bit.ly/sage-adebayo) RU![](https://images.unsplash.com/photo-1531746020798-e6953c6e8e04) ``` import { HStack } from "@chakra-ui/react" import { Avatar } from "@/components/ui/avatar" const Demo = () => { return ( <HStack gap="4"> <Avatar name="Dan Abramov" src="https://bit.ly/dan-abramov" shape="square" size="lg" /> <Avatar name="Sage Adebayo" src="https://bit.ly/sage-adebayo" shape="rounded" size="lg" /> <Avatar name="Random User" src="https://images.unsplash.com/photo-1531746020798-e6953c6e8e04" shape="full" size="lg" /> </HStack> ) } ``` ### [Fallback]() The initials of the name can be used as a fallback when the `src` prop is not provided or when the image fails to load. PreviewCode OK![](https://bit.ly/broken-link) SU![](https://bit.ly/broken-link) ![](https://bit.ly/broken-link) ``` import { HStack } from "@chakra-ui/react" import { Avatar } from "@/components/ui/avatar" const Demo = () => { return ( <HStack> <Avatar name="Oshigaki Kisame" src="https://bit.ly/broken-link" /> <Avatar name="Sasuke Uchiha" src="https://bit.ly/broken-link" colorPalette="teal" /> <Avatar src="https://bit.ly/broken-link" colorPalette="red" /> </HStack> ) } ``` ### [Random Color]() Combine the `colorPalette` prop with some custom logic to dynamically change the color of the avatar PreviewCode SN BL JL ``` import { HStack } from "@chakra-ui/react" import { Avatar } from "@/components/ui/avatar" const colorPalette = ["red", "blue", "green", "yellow", "purple", "orange"] const pickPalette = (name: string) => { const index = name.charCodeAt(0) % colorPalette.length return colorPalette[index] } const Demo = () => { return ( <HStack> <Avatar name="Shane Nelson" colorPalette={pickPalette("Shane Nelson")} /> <Avatar name="Brook Lesnar" colorPalette={pickPalette("Brook Lesnar")} /> <Avatar name="John Lennon" colorPalette={pickPalette("John Lennon")} /> </HStack> ) } ``` ### [Ring]() Use the `outline*` props to add a ring around the avatar PreviewCode R![](https://randomuser.me/api/portraits/men/70.jpg) R![](https://randomuser.me/api/portraits/men/54.jpg) R![](https://randomuser.me/api/portraits/men/42.jpg) ``` import { HStack, defineStyle } from "@chakra-ui/react" import { Avatar } from "@/components/ui/avatar" const ringCss = defineStyle({ outlineWidth: "2px", outlineColor: "colorPalette.500", outlineOffset: "2px", outlineStyle: "solid", }) const Demo = () => { return ( <HStack gap="4"> <Avatar name="Random" colorPalette="pink" src="https://randomuser.me/api/portraits/men/70.jpg" css={ringCss} /> <Avatar name="Random" colorPalette="green" src="https://randomuser.me/api/portraits/men/54.jpg" css={ringCss} /> <Avatar name="Random" colorPalette="blue" src="https://randomuser.me/api/portraits/men/42.jpg" css={ringCss} /> </HStack> ) } ``` ### [Group]() Use the `Group` component to group multiple avatars together PreviewCode US![](https://cdn.myanimelist.net/r/84x124/images/characters/9/131317.webp?s=d4b03c7291407bde303bc0758047f6bd) BA![](https://cdn.myanimelist.net/r/84x124/images/characters/7/284129.webp?s=a8998bf668767de58b33740886ca571c) UC![](https://cdn.myanimelist.net/r/84x124/images/characters/9/105421.webp?s=269ff1b2bb9abe3ac1bc443d3a76e863) +3 ``` import { Avatar, AvatarGroup } from "@/components/ui/avatar" const Demo = () => { return ( <AvatarGroup size="lg"> <Avatar src="https://cdn.myanimelist.net/r/84x124/images/characters/9/131317.webp?s=d4b03c7291407bde303bc0758047f6bd" name="Uchiha Sasuke" /> <Avatar src="https://cdn.myanimelist.net/r/84x124/images/characters/7/284129.webp?s=a8998bf668767de58b33740886ca571c" name="Baki Ani" /> <Avatar src="https://cdn.myanimelist.net/r/84x124/images/characters/9/105421.webp?s=269ff1b2bb9abe3ac1bc443d3a76e863" name="Uchiha Chan" /> <Avatar variant="solid" fallback="+3" /> </AvatarGroup> ) } ``` ### [Stacking]() When using the `AvatarGroup` component, you can use the `stacking` prop to change the stacking order of the avatars PreviewCode US![](https://cdn.myanimelist.net/r/84x124/images/characters/9/131317.webp?s=d4b03c7291407bde303bc0758047f6bd) BA![](https://cdn.myanimelist.net/r/84x124/images/characters/7/284129.webp?s=a8998bf668767de58b33740886ca571c) UC![](https://cdn.myanimelist.net/r/84x124/images/characters/9/105421.webp?s=269ff1b2bb9abe3ac1bc443d3a76e863) +3 US![](https://cdn.myanimelist.net/r/84x124/images/characters/9/131317.webp?s=d4b03c7291407bde303bc0758047f6bd) BA![](https://cdn.myanimelist.net/r/84x124/images/characters/7/284129.webp?s=a8998bf668767de58b33740886ca571c) UC![](https://cdn.myanimelist.net/r/84x124/images/characters/9/105421.webp?s=269ff1b2bb9abe3ac1bc443d3a76e863) +3 US![](https://cdn.myanimelist.net/r/84x124/images/characters/9/131317.webp?s=d4b03c7291407bde303bc0758047f6bd) BA![](https://cdn.myanimelist.net/r/84x124/images/characters/7/284129.webp?s=a8998bf668767de58b33740886ca571c) UC![](https://cdn.myanimelist.net/r/84x124/images/characters/9/105421.webp?s=269ff1b2bb9abe3ac1bc443d3a76e863) +3 ``` import { Stack } from "@chakra-ui/react" import { Avatar, AvatarGroup } from "@/components/ui/avatar" const Demo = () => { return ( <Stack> <AvatarGroup size="lg" stacking="last-on-top"> {items.map((item) => ( <Avatar key={item.name} src={item.src} name={item.name} /> ))} <Avatar fallback="+3" /> </AvatarGroup> <AvatarGroup size="lg" stacking="first-on-top"> {items.map((item) => ( <Avatar key={item.name} src={item.src} name={item.name} /> ))} <Avatar fallback="+3" /> </AvatarGroup> <AvatarGroup size="lg" spaceX="1" borderless> {items.map((item) => ( <Avatar key={item.name} src={item.src} name={item.name} /> ))} <Avatar fallback="+3" /> </AvatarGroup> </Stack> ) } const items = [ { src: "https://cdn.myanimelist.net/r/84x124/images/characters/9/131317.webp?s=d4b03c7291407bde303bc0758047f6bd", name: "Uchiha Sasuke", }, { src: "https://cdn.myanimelist.net/r/84x124/images/characters/7/284129.webp?s=a8998bf668767de58b33740886ca571c", name: "Baki Ani", }, { src: "https://cdn.myanimelist.net/r/84x124/images/characters/9/105421.webp?s=269ff1b2bb9abe3ac1bc443d3a76e863", name: "Uchiha Chan", }, ] ``` ### [Persona]() Here's an example of how to use the `Avatar` component to display a user persona. PreviewCode JM![](https://i.pravatar.cc/300?u=iu) John Mason [email protected] MJ![](https://i.pravatar.cc/300?u=po) Melissa Jones [email protected] ``` import { HStack, Stack, Text } from "@chakra-ui/react" import { Avatar } from "@/components/ui/avatar" const Demo = () => { return ( <Stack gap="8"> {users.map((user) => ( <HStack key={user.email} gap="4"> <Avatar name={user.name} size="lg" src={user.avatar} /> <Stack gap="0"> <Text fontWeight="medium">{user.name}</Text> <Text color="fg.muted" textStyle="sm"> {user.email} </Text> </Stack> </HStack> ))} </Stack> ) } const users = [ { id: "1", name: "John Mason", email: "[email protected]", avatar: "https://i.pravatar.cc/300?u=iu", }, { id: "2", name: "Melissa Jones", email: "[email protected]", avatar: "https://i.pravatar.cc/300?u=po", }, ] ``` ### [Badge]() Show a badge on the right corner of the avatar by composing the `Float` and `Circle` components PreviewCode DA ``` import { Avatar, Circle, Float } from "@chakra-ui/react" const Demo = () => { return ( <Avatar.Root colorPalette="green" variant="subtle"> <Avatar.Fallback>DA</Avatar.Fallback> <Float placement="bottom-end" offsetX="1" offsetY="1"> <Circle bg="green.500" size="8px" outline="0.2em solid" outlineColor="bg" /> </Float> </Avatar.Root> ) } ``` ### [Overflow]() Here's an example of how to handle an overflow of avatars by composing the `Menu` and `Avatar` components. PreviewCode NU SH KH +2 HH Hinata Hyuga SN Shikamaru Nara ``` import { Group } from "@chakra-ui/react" import { Avatar } from "@/components/ui/avatar" import { MenuContent, MenuItem, MenuRoot, MenuTrigger, } from "@/components/ui/menu" const names = [ "Naruto Uzumaki", "Sakura Haruno", "Kakashi Hatake", "Hinata Hyuga", "Shikamaru Nara", ] const maxAvatars = 3 const Demo = () => { const { items, overflow } = partition(names, maxAvatars) return ( <Group gap="0" spaceX="2"> {items.map((item) => ( <Avatar key={item} name={item} colorPalette={pickPalette(item)} /> ))} {overflow.length > 0 && ( <MenuRoot positioning={{ placement: "bottom" }}> <MenuTrigger rounded="full" focusRing="outside"> <Avatar variant="outline" fallback={`+${overflow.length}`} /> </MenuTrigger> <MenuContent> {overflow.map((item) => ( <MenuItem value={item} key={item}> <Avatar size="xs" name={item} colorPalette={pickPalette(item)} /> {item} </MenuItem> ))} </MenuContent> </MenuRoot> )} </Group> ) } const colorPalette = ["red", "blue", "green", "yellow", "purple", "orange"] const pickPalette = (name: string) => { const index = name.charCodeAt(0) % colorPalette.length return colorPalette[index] } const partition = (arr: string[], max: number) => { const items = [] const overflow = [] for (const item of arr) { if (items.length < max) items.push(item) else overflow.push(item) } return { items, overflow } } ``` ### [Without Snippet]() Here's an example of how to use the `Avatar` without the snippet. PreviewCode ![](https://bit.ly/sage-adebayo)SA ``` import { Avatar } from "@chakra-ui/react" const Demo = () => { return ( <Avatar.Root> <Avatar.Image src="https://bit.ly/sage-adebayo" /> <Avatar.Fallback>SA</Avatar.Fallback> </Avatar.Root> ) } ``` ## [Props]() ### [Root]() PropDefaultType`colorPalette``'gray'` `'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink' | 'accent'` The color palette of the component `size``'md'` `'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl'` The size of the component `variant``'subtle'` `'solid' | 'subtle' | 'outline'` The variant of the component `shape``'full'` `'square' | 'rounded' | 'full'` The shape of the component `asChild` `boolean` Use the provided child element as the default rendered element, combining their props and behavior. For more details, read our [Composition](https://www.chakra-ui.com/docs/guides/composition) guide. `ids` `Partial<{ root: string; image: string; fallback: string }>` The ids of the elements in the avatar. Useful for composition. `onStatusChange` `(details: StatusChangeDetails) => void` Functional called when the image loading status changes. `borderless` `'true' | 'false'` The borderless of the component `as` `React.ElementType` The underlying element to render. `unstyled` `boolean` Whether to remove the component's style. ### [Fallback]() PropDefaultType`asChild` `boolean` Use the provided child element as the default rendered element, combining their props and behavior. For more details, read our [Composition](https://www.chakra-ui.com/docs/guides/composition) guide. `name` `string` `icon` `React.ReactElement` ### [Image]() PropDefaultType`asChild` `boolean` Use the provided child element as the default rendered element, combining their props and behavior. For more details, read our [Composition](https://www.chakra-ui.com/docs/guides/composition) guide. [Previous \ Alert](https://www.chakra-ui.com/docs/components/alert) [Next \ Badge](https://www.chakra-ui.com/docs/components/badge)
https://www.chakra-ui.com/docs/components/accordion
1. Components 2. Accordion # Accordion Used to show and hide sections of related content on a page [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/accordion)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Fcomponents-accordion--basic)[Recipe](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/theme/recipes/accordion.ts)[Ark](https://ark-ui.com/react/docs/components/accordion) PreviewCode First Item Some value 1... Second Item Some value 2... Third Item Some value 3... ``` import { AccordionItem, AccordionItemContent, AccordionItemTrigger, AccordionRoot, } from "@/components/ui/accordion" const Demo = () => { return ( <AccordionRoot collapsible defaultValue={["b"]}> {items.map((item, index) => ( <AccordionItem key={index} value={item.value}> <AccordionItemTrigger>{item.title}</AccordionItemTrigger> <AccordionItemContent>{item.text}</AccordionItemContent> </AccordionItem> ))} </AccordionRoot> ) } const items = [ { value: "a", title: "First Item", text: "Some value 1..." }, { value: "b", title: "Second Item", text: "Some value 2..." }, { value: "c", title: "Third Item", text: "Some value 3..." }, ] ``` ## [Setup]() If you don't already have the snippet, run the following command to add the `accordion` snippet ``` npx @chakra-ui/cli snippet add accordion ``` The snippet includes a closed component composition for the `Accordion` component. ## [Usage]() ``` import { AccordionItem, AccordionItemContent, AccordionItemTrigger, AccordionRoot, } from "@/components/ui/accordion" ``` ``` <AccordionRoot> <AccordionItem> <AccordionItemTrigger /> <AccordionItemContent /> </AccordionItem> </AccordionRoot> ``` ## [Examples]() ### [Controlled]() Set the accordion that shows up by default. PreviewCode Expanded: second-item First Item Some value 1... Second Item Some value 2... Third Item Some value 3... ``` "use client" import { Stack, Text } from "@chakra-ui/react" import { AccordionItem, AccordionItemContent, AccordionItemTrigger, AccordionRoot, } from "@/components/ui/accordion" import { useState } from "react" const Demo = () => { const [value, setValue] = useState(["second-item"]) return ( <Stack gap="4"> <Text fontWeight="medium">Expanded: {value.join(", ")}</Text> <AccordionRoot value={value} onValueChange={(e) => setValue(e.value)}> {items.map((item, index) => ( <AccordionItem key={index} value={item.value}> <AccordionItemTrigger>{item.title}</AccordionItemTrigger> <AccordionItemContent>{item.text}</AccordionItemContent> </AccordionItem> ))} </AccordionRoot> </Stack> ) } const items = [ { value: "first-item", title: "First Item", text: "Some value 1..." }, { value: "second-item", title: "Second Item", text: "Some value 2..." }, { value: "third-item", title: "Third Item", text: "Some value 3..." }, ] ``` ### [With Icon]() Use the `AccordionItemIcon` to add an icon to each accordion item. PreviewCode ## Product details Product Info Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur nec odio vel dui euismod fermentum. Stats Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur nec odio vel dui euismod fermentum. ``` import { Heading, Icon, Stack } from "@chakra-ui/react" import { AccordionItem, AccordionItemContent, AccordionItemTrigger, AccordionRoot, } from "@/components/ui/accordion" import { LuBarChart, LuTags } from "react-icons/lu" const Demo = () => { return ( <Stack width="full" maxW="400px"> <Heading size="md">Product details</Heading> <AccordionRoot collapsible defaultValue={["info"]}> {items.map((item) => ( <AccordionItem key={item.value} value={item.value}> <AccordionItemTrigger> <Icon fontSize="lg" color="fg.subtle"> {item.icon} </Icon> {item.title} </AccordionItemTrigger> <AccordionItemContent>{item.content}</AccordionItemContent> </AccordionItem> ))} </AccordionRoot> </Stack> ) } const items = [ { value: "info", icon: <LuTags />, title: "Product Info", content: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur nec odio vel dui euismod fermentum.", }, { value: "stats", icon: <LuBarChart />, title: "Stats", content: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur nec odio vel dui euismod fermentum.", }, ] ``` ### [Expand Multiple Items]() Use the `multiple` prop to allow multiple items to be expanded at once. PreviewCode First Item Some value 1... Second Item Some value 2... Third Item Some value 3... ``` import { AccordionItem, AccordionItemContent, AccordionItemTrigger, AccordionRoot, } from "@/components/ui/accordion" const Demo = () => { return ( <AccordionRoot multiple defaultValue={["b"]}> {items.map((item, index) => ( <AccordionItem key={index} value={item.value}> <AccordionItemTrigger>{item.title}</AccordionItemTrigger> <AccordionItemContent>{item.text}</AccordionItemContent> </AccordionItem> ))} </AccordionRoot> ) } const items = [ { value: "a", title: "First Item", text: "Some value 1..." }, { value: "b", title: "Second Item", text: "Some value 2..." }, { value: "c", title: "Third Item", text: "Some value 3..." }, ] ``` ### [Sizes]() Use the `size` prop to change the size of the accordion. PreviewCode sm First Item Some value 1... Second Item Some value 2... Third Item Some value 3... md First Item Some value 1... Second Item Some value 2... Third Item Some value 3... lg First Item Some value 1... Second Item Some value 2... Third Item Some value 3... ``` import { For, Stack, Text } from "@chakra-ui/react" import { AccordionItem, AccordionItemContent, AccordionItemTrigger, AccordionRoot, } from "@/components/ui/accordion" const Demo = () => { return ( <Stack gap="8"> <For each={["sm", "md", "lg"]}> {(size) => ( <Stack gap="2"> <Text fontWeight="semibold">{size}</Text> <AccordionRoot size={size} key={size} collapsible defaultValue={["b"]} > {items.map((item, index) => ( <AccordionItem key={index} value={item.value}> <AccordionItemTrigger>{item.title}</AccordionItemTrigger> <AccordionItemContent>{item.text}</AccordionItemContent> </AccordionItem> ))} </AccordionRoot> </Stack> )} </For> </Stack> ) } const items = [ { value: "a", title: "First Item", text: "Some value 1..." }, { value: "b", title: "Second Item", text: "Some value 2..." }, { value: "c", title: "Third Item", text: "Some value 3..." }, ] ``` ### [Variants]() Use the `variant` prop to change the visual style of the accordion. Values can be either `outline`, `elevated`, `contained` or `plain`. PreviewCode outline First Item Some value 1... Second Item Some value 2... Third Item Some value 3... subtle First Item Some value 1... Second Item Some value 2... Third Item Some value 3... enclosed First Item Some value 1... Second Item Some value 2... Third Item Some value 3... plain First Item Some value 1... Second Item Some value 2... Third Item Some value 3... ``` import { For, Stack, Text } from "@chakra-ui/react" import { AccordionItem, AccordionItemContent, AccordionItemTrigger, AccordionRoot, } from "@/components/ui/accordion" const Demo = () => { return ( <Stack gap="8"> <For each={["outline", "subtle", "enclosed", "plain"]}> {(variant) => ( <Stack gap="2"> <Text fontWeight="semibold">{variant}</Text> <AccordionRoot variant={variant} key={variant} collapsible defaultValue={["b"]} > {items.map((item, index) => ( <AccordionItem key={index} value={item.value}> <AccordionItemTrigger>{item.title}</AccordionItemTrigger> <AccordionItemContent>{item.text}</AccordionItemContent> </AccordionItem> ))} </AccordionRoot> </Stack> )} </For> </Stack> ) } const items = [ { value: "a", title: "First Item", text: "Some value 1..." }, { value: "b", title: "Second Item", text: "Some value 2..." }, { value: "c", title: "Third Item", text: "Some value 3..." }, ] ``` ### [Disabled Item]() Pass the `disabled` prop to disable an accordion item to prevent it from being expanded or collapsed. PreviewCode First Item Some value 1... Second Item Some value 2... Third Item Some value 3... ``` import { AccordionItem, AccordionItemContent, AccordionItemTrigger, AccordionRoot, } from "@/components/ui/accordion" const Demo = () => { return ( <AccordionRoot collapsible defaultValue={["b"]}> {items.map((item, index) => ( <AccordionItem key={index} value={item.value} disabled={item.disabled}> <AccordionItemTrigger>{item.title}</AccordionItemTrigger> <AccordionItemContent>{item.text}</AccordionItemContent> </AccordionItem> ))} </AccordionRoot> ) } const items = [ { value: "a", title: "First Item", text: "Some value 1..." }, { value: "b", title: "Second Item", text: "Some value 2..." }, { value: "c", title: "Third Item", text: "Some value 3...", disabled: true }, ] ``` ### [With Avatar]() Here's an example of composing an accordion with an avatar. PreviewCode A![](https://i.pravatar.cc/150?u=a) Alex Lorem ipsum odor amet, consectetuer adipiscing elit. Convallis fames condimentum vehicula convallis mauris est. Luctus porttitor feugiat facilisi efficitur etiam luctus nisl pretium. Tincidunt iaculis vehicula fermentum dignissim vitae, donec vestibulum elit. Himenaeos sit vulputate laoreet; justo morbi blandit pharetra. Torquent finibus lobortis lacinia commodo non volutpat lacinia. Metus ultrices molestie dui at cursus nunc rhoncus. Eget himenaeos ut turpis pretium ridiculus ultricies molestie tristique. B![](https://i.pravatar.cc/150?u=b) Benji Top Rated Lorem ipsum odor amet, consectetuer adipiscing elit. Facilisis euismod placerat vivamus orci lectus ad. Augue fames enim rhoncus accumsan nunc aliquam. Mollis a semper himenaeos sociosqu non praesent rhoncus ad. Tristique curabitur inceptos magnis bibendum curae lacinia condimentum conubia. Habitasse libero erat vestibulum justo viverra. Cursus maecenas sociosqu; maecenas ipsum ac eros convallis. Dictumst dolor enim curabitur vehicula congue. C![](https://i.pravatar.cc/150?u=c) Charlie Lorem ipsum odor amet, consectetuer adipiscing elit. Facilisi tristique augue integer cursus penatibus nulla. Odio metus fermentum habitant et penatibus habitant tincidunt hac. Himenaeos class erat varius; montes aliquam sollicitudin auctor. Rhoncus mi taciti lectus commodo, praesent ridiculus taciti taciti. Adipiscing urna dui habitasse leo tellus, ornare arcu suscipit. Lobortis suspendisse pellentesque lacus est posuere phasellus adipiscing. Massa ante pretium metus posuere tempus mi. ``` import { Badge, HStack } from "@chakra-ui/react" import { AccordionItem, AccordionItemContent, AccordionItemTrigger, AccordionRoot, } from "@/components/ui/accordion" import { Avatar } from "@/components/ui/avatar" import { LuTrophy } from "react-icons/lu" import { LoremIpsum } from "react-lorem-ipsum" const Demo = () => { return ( <AccordionRoot collapsible defaultValue={["b"]}> {items.map((item, index) => ( <AccordionItem key={index} value={item.name}> <AccordionItemTrigger> <Avatar shape="rounded" src={item.image} name={item.name} /> <HStack> {item.name}{" "} {item.topRated && ( <Badge colorPalette="green"> <LuTrophy /> Top Rated </Badge> )} </HStack> </AccordionItemTrigger> <AccordionItemContent>{item.bio}</AccordionItemContent> </AccordionItem> ))} </AccordionRoot> ) } const items = [ { name: "Alex", bio: <LoremIpsum />, image: "https://i.pravatar.cc/150?u=a", topRated: false, }, { name: "Benji", bio: <LoremIpsum />, image: "https://i.pravatar.cc/150?u=b", topRated: true, }, { name: "Charlie", bio: <LoremIpsum />, image: "https://i.pravatar.cc/150?u=c", topRated: false, }, ] ``` ### [With Subtext]() Here's an example of adding a subtext to an accordion item. PreviewCode First Item Click to expand Lorem ipsum odor amet, consectetuer adipiscing elit. In nec risus massa adipiscing ac hendrerit sapien litora. In ac augue nec molestie mauris diam sit. Vel aptent urna elementum hac ridiculus tellus dis? Sit ut nec eleifend massa tristique natoque eu netus. Tincidunt eu dignissim dui malesuada gravida potenti duis nullam. Duis placerat semper a a felis eleifend nec rutrum. Mus porta eget ac nisi aliquam. Second Item Click to expand Lorem ipsum odor amet, consectetuer adipiscing elit. Integer aliquet eu tortor feugiat dapibus mollis vulputate. Platea fermentum lacinia aptent ipsum sit; per turpis aliquet. Ultricies id eros varius nullam dictum mauris ullamcorper commodo. Magna mattis arcu hac tempor sodales purus massa velit porttitor. Sit posuere tincidunt quisque sit euismod primis interdum fusce. Sagittis habitant sagittis sociosqu adipiscing dis habitant scelerisque bibendum. Massa pharetra sem convallis vulputate aptent at. Suspendisse torquent quam potenti mi lobortis ipsum faucibus id odio. Third Item Click to expand Lorem ipsum odor amet, consectetuer adipiscing elit. Tempus nulla sollicitudin class dictum velit bibendum pharetra primis. Ultricies feugiat suspendisse nisl maximus dolor in scelerisque. Odio conubia nisi magnis commodo sollicitudin per blandit. Velit curae sit praesent bibendum luctus felis interdum. Alectus commodo habitant rutrum mattis mus. Magnis inceptos lacinia montes turpis litora amet faucibus cras. Senectus neque inceptos faucibus luctus etiam. ``` import { Stack, Text } from "@chakra-ui/react" import { AccordionItem, AccordionItemContent, AccordionItemTrigger, AccordionRoot, } from "@/components/ui/accordion" import { LoremIpsum } from "react-lorem-ipsum" const items = [ { value: "a", title: "First Item", text: <LoremIpsum p={1} /> }, { value: "b", title: "Second Item", text: <LoremIpsum p={1} /> }, { value: "c", title: "Third Item", text: <LoremIpsum p={1} /> }, ] const Demo = () => { return ( <AccordionRoot collapsible> {items.map((item, index) => ( <AccordionItem key={index} value={item.value}> <AccordionItemTrigger> <Stack gap="1"> <Text>{item.title}</Text> <Text fontSize="sm" color="fg.muted"> Click to expand </Text> </Stack> </AccordionItemTrigger> <AccordionItemContent>{item.text}</AccordionItemContent> </AccordionItem> ))} </AccordionRoot> ) } ``` ### [With Actions]() Here's an example of adding actions to an accordion item trigger. PreviewCode First Item Action Lorem ipsum odor amet, consectetuer adipiscing elit. Cursus posuere facilisi condimentum penatibus suscipit lacus. Mollis primis eu rutrum, inceptos nullam mauris. Diam habitant arcu aliquam fringilla eu at. Laoreet lacus proin venenatis sociosqu ridiculus. Risus accumsan accumsan aliquet hac primis accumsan mauris accumsan. Facilisis ridiculus consectetur a vehicula natoque. Second Item Action Lorem ipsum odor amet, consectetuer adipiscing elit. Massa lorem etiam; urna inceptos imperdiet lobortis. Lacinia purus suscipit facilisis vehicula massa. Enim dignissim in cubilia turpis quis fusce at. Gravida turpis sed mauris hac hendrerit, euismod neque nam. Ultricies tortor potenti cubilia morbi elementum, euismod sapien cursus arcu. Fusce tristique orci vel rhoncus nam, purus class magna. Auctor vulputate placerat aliquet placerat sem sapien porta. Third Item Action Lorem ipsum odor amet, consectetuer adipiscing elit. Dis hendrerit mattis nibh potenti pulvinar phasellus consectetur nibh. Natoque dui nisi condimentum interdum proin sem a nec ultricies. Aliquam ridiculus convallis ut consectetur viverra taciti in. Nulla platea imperdiet molestie eu euismod platea. Dictumst enim pretium, dapibus venenatis habitant penatibus malesuada purus. Fusce vel etiam risus habitant scelerisque ullamcorper praesent. Cursus dignissim gravida dis velit leo faucibus commodo diam erat. ``` import { AbsoluteCenter, Box, Button } from "@chakra-ui/react" import { AccordionItem, AccordionItemContent, AccordionItemTrigger, AccordionRoot, } from "@/components/ui/accordion" import LoremIpsum from "react-lorem-ipsum" const Demo = () => { return ( <AccordionRoot spaceY="4" variant="plain" collapsible defaultValue={["b"]}> {items.map((item, index) => ( <AccordionItem key={index} value={item.value}> <Box position="relative"> <AccordionItemTrigger indicatorPlacement="start"> {item.title} </AccordionItemTrigger> <AbsoluteCenter axis="vertical" insetEnd="0"> <Button variant="subtle" colorPalette="blue"> Action </Button> </AbsoluteCenter> </Box> <AccordionItemContent>{item.text}</AccordionItemContent> </AccordionItem> ))} </AccordionRoot> ) } const items = [ { value: "a", title: "First Item", text: <LoremIpsum /> }, { value: "b", title: "Second Item", text: <LoremIpsum /> }, { value: "c", title: "Third Item", text: <LoremIpsum /> }, ] ``` ### [Without Snippet]() Here's how to setup the accordion without using the snippet. PreviewCode First Item Some value 1... Second Item Some value 2... Third Item Some value 3... ``` import { Accordion } from "@chakra-ui/react" const Demo = () => { return ( <Accordion.Root collapsible defaultValue={["b"]}> {items.map((item, index) => ( <Accordion.Item key={index} value={item.value}> <Accordion.ItemTrigger> {item.title} <Accordion.ItemIndicator /> </Accordion.ItemTrigger> <Accordion.ItemContent> <Accordion.ItemBody>{item.text}</Accordion.ItemBody> </Accordion.ItemContent> </Accordion.Item> ))} </Accordion.Root> ) } const items = [ { value: "a", title: "First Item", text: "Some value 1..." }, { value: "b", title: "Second Item", text: "Some value 2..." }, { value: "c", title: "Third Item", text: "Some value 3..." }, ] ``` ## [Props]() ### [Root]() PropDefaultType`collapsible``false` `boolean` Whether an accordion item can be closed after it has been expanded. `lazyMount``false` `boolean` Whether to enable lazy mounting `multiple``false` `boolean` Whether multple accordion items can be expanded at the same time. `orientation``'\'vertical\''` `'horizontal' | 'vertical'` The orientation of the accordion items. `unmountOnExit``false` `boolean` Whether to unmount on exit. `colorPalette``'gray'` `'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink' | 'accent'` The color palette of the component `variant``'outline'` `'outline' | 'subtle' | 'enclosed' | 'plain'` The variant of the component `size``'md'` `'sm' | 'md' | 'lg'` The size of the component `asChild` `boolean` Use the provided child element as the default rendered element, combining their props and behavior. For more details, read our [Composition](https://www.chakra-ui.com/docs/guides/composition) guide. `defaultValue` `string[]` The initial value of the accordion when it is first rendered. Use when you do not need to control the state of the accordion. `disabled` `boolean` Whether the accordion items are disabled `id` `string` The unique identifier of the machine. `ids` `Partial<{ root: string item(value: string): string itemContent(value: string): string itemTrigger(value: string): string }>` The ids of the elements in the accordion. Useful for composition. `onFocusChange` `(details: FocusChangeDetails) => void` The callback fired when the focused accordion item changes. `onValueChange` `(details: ValueChangeDetails) => void` The callback fired when the state of expanded/collapsed accordion items changes. `value` `string[]` The \`value\` of the accordion items that are currently being expanded. ### [Item]() PropDefaultType`value`* `string` The value of the accordion item. `asChild` `boolean` Use the provided child element as the default rendered element, combining their props and behavior. For more details, read our [Composition](https://www.chakra-ui.com/docs/guides/composition) guide. `disabled` `boolean` Whether the accordion item is disabled. [Previous \ Text](https://www.chakra-ui.com/docs/components/text) [Next \ Action Bar](https://www.chakra-ui.com/docs/components/action-bar)
https://www.chakra-ui.com/docs/components/breadcrumb
1. Components 2. Breadcrumb # Breadcrumb Used to display a page's location within a site's hierarchical structure [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/breadcrumb)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Fcomponents-breadcrumb--basic)[Recipe](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/theme/recipes/breadcrumb.ts) PreviewCode 1. [Docs]() 2. [Components]() 3. Props ``` import { BreadcrumbCurrentLink, BreadcrumbLink, BreadcrumbRoot, } from "@/components/ui/breadcrumb" const Demo = () => { return ( <BreadcrumbRoot> <BreadcrumbLink href="#">Docs</BreadcrumbLink> <BreadcrumbLink href="#">Components</BreadcrumbLink> <BreadcrumbCurrentLink>Props</BreadcrumbCurrentLink> </BreadcrumbRoot> ) } ``` ## [Setup]() If you don't already have the snippet, run the following command to add the `breadcrumb` snippet ``` npx @chakra-ui/cli snippet add breadcrumb ``` The snippet includes a closed component composition for the `Breadcrumb` component. ## [Usage]() ``` import { BreadcrumbCurrentLink, BreadcrumbLink, BreadcrumbRoot, } from "@/components/ui/breadcrumb" ``` ``` <BreadcrumbRoot> <BreadcrumbLink href="#">Docs</BreadcrumbLink> <BreadcrumbLink href="#">Components</BreadcrumbLink> <BreadcrumbCurrentLink>Props</BreadcrumbCurrentLink> </BreadcrumbRoot> ``` ## [Examples]() ### [Sizes]() Use the `size` prop to change the size of the breadcrumb component PreviewCode 1. [Docs]() 2. [Components]() 3. Props <!--THE END--> 1. [Docs]() 2. [Components]() 3. Props <!--THE END--> 1. [Docs]() 2. [Components]() 3. Props ``` import { Stack } from "@chakra-ui/react" import { BreadcrumbCurrentLink, BreadcrumbLink, BreadcrumbRoot, } from "@/components/ui/breadcrumb" const Demo = () => { return ( <Stack> <BreadcrumbRoot size="sm"> <BreadcrumbLink href="#">Docs</BreadcrumbLink> <BreadcrumbLink href="#">Components</BreadcrumbLink> <BreadcrumbCurrentLink>Props</BreadcrumbCurrentLink> </BreadcrumbRoot> <BreadcrumbRoot size="md"> <BreadcrumbLink href="#">Docs</BreadcrumbLink> <BreadcrumbLink href="#">Components</BreadcrumbLink> <BreadcrumbCurrentLink>Props</BreadcrumbCurrentLink> </BreadcrumbRoot> <BreadcrumbRoot size="lg"> <BreadcrumbLink href="#">Docs</BreadcrumbLink> <BreadcrumbLink href="#">Components</BreadcrumbLink> <BreadcrumbCurrentLink>Props</BreadcrumbCurrentLink> </BreadcrumbRoot> </Stack> ) } ``` ### [Variants]() Use the `variant` prop to change the appearance of the breadcrumb component PreviewCode 1. [Docs]() 2. [Components]() 3. Props <!--THE END--> 1. [Docs]() 2. [Components]() 3. Props ``` import { Stack } from "@chakra-ui/react" import { BreadcrumbCurrentLink, BreadcrumbLink, BreadcrumbRoot, } from "@/components/ui/breadcrumb" const Demo = () => { return ( <Stack> <BreadcrumbRoot variant="plain"> <BreadcrumbLink href="#">Docs</BreadcrumbLink> <BreadcrumbLink href="#">Components</BreadcrumbLink> <BreadcrumbCurrentLink>Props</BreadcrumbCurrentLink> </BreadcrumbRoot> <BreadcrumbRoot variant="underline"> <BreadcrumbLink href="#">Docs</BreadcrumbLink> <BreadcrumbLink href="#">Components</BreadcrumbLink> <BreadcrumbCurrentLink>Props</BreadcrumbCurrentLink> </BreadcrumbRoot> </Stack> ) } ``` ### [With Separator]() Use the `separator` prop to add the separator PreviewCode 1. [Docs]() 2. [Components]() 3. Props ``` import { BreadcrumbCurrentLink, BreadcrumbLink, BreadcrumbRoot, } from "@/components/ui/breadcrumb" import { LiaSlashSolid } from "react-icons/lia" const Demo = () => { return ( <BreadcrumbRoot separator={<LiaSlashSolid />}> <BreadcrumbLink href="#">Docs</BreadcrumbLink> <BreadcrumbLink href="#">Components</BreadcrumbLink> <BreadcrumbCurrentLink>Props</BreadcrumbCurrentLink> </BreadcrumbRoot> ) } ``` ### [Icon]() Here's how you can add an icon to the breadcrumb PreviewCode 1. [Home]() 2. [Men Wear]() 3. Trousers ``` import { BreadcrumbCurrentLink, BreadcrumbLink, BreadcrumbRoot, } from "@/components/ui/breadcrumb" import { LuHome, LuShirt } from "react-icons/lu" const Demo = () => { return ( <BreadcrumbRoot> <BreadcrumbLink href="#"> <LuHome /> Home </BreadcrumbLink> <BreadcrumbLink href="#"> <LuShirt /> Men Wear </BreadcrumbLink> <BreadcrumbCurrentLink>Trousers</BreadcrumbCurrentLink> </BreadcrumbRoot> ) } ``` ### [Menu]() Compose the breadcrumb with menu component PreviewCode 1. [Docs]() 2. / 3. Components Theme Props Customization 4. / 5. Props ``` import { BreadcrumbCurrentLink, BreadcrumbLink, BreadcrumbRoot, } from "@/components/ui/breadcrumb" import { MenuContent, MenuItem, MenuRoot, MenuTrigger, } from "@/components/ui/menu" import { LuChevronDown } from "react-icons/lu" const Demo = () => { return ( <BreadcrumbRoot separator="/" separatorGap="4"> <BreadcrumbLink href="#">Docs</BreadcrumbLink> <MenuRoot> <MenuTrigger asChild> <BreadcrumbLink as="button"> Components <LuChevronDown /> </BreadcrumbLink> </MenuTrigger> <MenuContent> <MenuItem value="theme">Theme</MenuItem> <MenuItem value="props">Props</MenuItem> <MenuItem value="custom">Customization</MenuItem> </MenuContent> </MenuRoot> <BreadcrumbCurrentLink>Props</BreadcrumbCurrentLink> </BreadcrumbRoot> ) } ``` ### [Ellipsis]() Render the `BreadcrumbEllipsis` component to show an ellipsis PreviewCode 1. [Docs]() 2. [Components]() 3. Props ``` import { BreadcrumbCurrentLink, BreadcrumbEllipsis, BreadcrumbLink, BreadcrumbRoot, } from "@/components/ui/breadcrumb" const Demo = () => { return ( <BreadcrumbRoot> <BreadcrumbLink href="#">Docs</BreadcrumbLink> <BreadcrumbLink href="#">Components</BreadcrumbLink> <BreadcrumbEllipsis /> <BreadcrumbCurrentLink>Props</BreadcrumbCurrentLink> </BreadcrumbRoot> ) } ``` ### [Routing Library]() Use the `asChild` prop to change the underlying breadcrumb link ``` import { Link } from "next/link" export const Example = () => { return ( <BreadcrumbRoot> <BreadcrumbLink asChild> <Link href="/docs">Docs</Link> </BreadcrumbLink> </BreadcrumbRoot> ) } ``` ### [Without Snippet]() If you don't want to use the snippet, you can use the `Breadcrumb` component from the `@chakra-ui/react` package. PreviewCode 1. [Docs]() 2. [Components]() 3. [Props]() ``` import { Breadcrumb } from "@chakra-ui/react" const Demo = () => { return ( <Breadcrumb.Root> <Breadcrumb.List> <Breadcrumb.Item> <Breadcrumb.Link href="#">Docs</Breadcrumb.Link> </Breadcrumb.Item> <Breadcrumb.Separator /> <Breadcrumb.Item> <Breadcrumb.Link href="#">Components</Breadcrumb.Link> </Breadcrumb.Item> <Breadcrumb.Separator /> <Breadcrumb.Item> <Breadcrumb.Link href="#">Props</Breadcrumb.Link> </Breadcrumb.Item> </Breadcrumb.List> </Breadcrumb.Root> ) } ``` ## [Props]() ### [Root]() PropDefaultType`colorPalette``'gray'` `'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink' | 'accent'` The color palette of the component `variant``'plain'` `'underline' | 'plain'` The variant of the component `size``'md'` `'sm' | 'md' | 'lg'` The size of the component `separator` `React.ReactNode` `separatorGap` `SystemStyleObject['gap']` `as` `React.ElementType` The underlying element to render. `asChild` `boolean` Use the provided child element as the default rendered element, combining their props and behavior. For more details, read our [Composition](https://www.chakra-ui.com/docs/guides/composition) guide. `unstyled` `boolean` Whether to remove the component's style. [Previous \ Badge](https://www.chakra-ui.com/docs/components/badge) [Next \ Button](https://www.chakra-ui.com/docs/components/button)
https://www.chakra-ui.com/docs/components/button
1. Components 2. Button # Button Used to trigger an action or event [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/button)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Fcomponents-button--basic)[Recipe](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/theme/recipes/button.ts) PreviewCode Button ``` import { Button } from "@chakra-ui/react" const Demo = () => { return <Button>Button</Button> } ``` ## [Setup]() If you don't already have the snippet, run the following command to add the `button` snippet ``` npx @chakra-ui/cli snippet add button ``` The snippet includes enhances the Button with `loading` and `loadingText` props. ## [Usage]() ``` import { Button } from "@/components/ui/button" ``` ``` <Button>Click me</Button> ``` ## [Examples]() ### [Sizes]() Use the `size` prop to change the size of the button. PreviewCode Button (xs)Button (sm)Button (md)Button (lg)Button (xl) ``` import { HStack } from "@chakra-ui/react" import { Button } from "@/components/ui/button" const Demo = () => { return ( <HStack wrap="wrap" gap="6"> <Button size="xs">Button (xs)</Button> <Button size="sm">Button (sm)</Button> <Button size="md">Button (md)</Button> <Button size="lg">Button (lg)</Button> <Button size="xl">Button (xl)</Button> </HStack> ) } ``` ### [Variants]() Use the `variant` prop to change the visual style of the Button. PreviewCode SolidSubtleSurfaceOutlineGhostPlain ``` import { HStack } from "@chakra-ui/react" import { Button } from "@/components/ui/button" const Demo = () => { return ( <HStack wrap="wrap" gap="6"> <Button variant="solid">Solid</Button> <Button variant="subtle">Subtle</Button> <Button variant="surface">Surface</Button> <Button variant="outline">Outline</Button> <Button variant="ghost">Ghost</Button> <Button variant="plain">Plain</Button> </HStack> ) } ``` ### [Icon]() Use icons within a button PreviewCode EmailCall us ``` import { HStack } from "@chakra-ui/react" import { Button } from "@/components/ui/button" import { RiArrowRightLine, RiMailLine } from "react-icons/ri" const Demo = () => { return ( <HStack> <Button colorPalette="teal" variant="solid"> <RiMailLine /> Email </Button> <Button colorPalette="teal" variant="outline"> Call us <RiArrowRightLine /> </Button> </HStack> ) } ``` ### [Color]() Use the `colorPalette` prop to change the color of the button PreviewCode gray ButtonButtonButtonButton red ButtonButtonButtonButton green ButtonButtonButtonButton blue ButtonButtonButtonButton teal ButtonButtonButtonButton pink ButtonButtonButtonButton purple ButtonButtonButtonButton cyan ButtonButtonButtonButton orange ButtonButtonButtonButton yellow ButtonButtonButtonButton ``` import { Stack, Text } from "@chakra-ui/react" import { colorPalettes } from "compositions/lib/color-palettes" import { Button } from "@/components/ui/button" const Demo = () => { return ( <Stack gap="2" align="flex-start"> {colorPalettes.map((colorPalette) => ( <Stack align="center" key={colorPalette} direction="row" gap="10"> <Text minW="8ch">{colorPalette}</Text> <Button colorPalette={colorPalette}>Button</Button> <Button colorPalette={colorPalette} variant="outline"> Button </Button> <Button colorPalette={colorPalette} variant="surface"> Button </Button> <Button colorPalette={colorPalette} variant="subtle"> Button </Button> </Stack> ))} </Stack> ) } ``` ### [Loading]() Use the `loading` and `loadingText` prop to show a loading spinner PreviewCode Click meSaving... ``` import { Stack } from "@chakra-ui/react" import { Button } from "@/components/ui/button" const Demo = () => { return ( <Stack direction="row" gap="4" align="center"> <Button loading>Click me</Button> <Button loading loadingText="Saving..."> Click me </Button> </Stack> ) } ``` ### [Group]() Use the `Group` component to group buttons together PreviewCode Button ``` import { Group, IconButton } from "@chakra-ui/react" import { Button } from "@/components/ui/button" import { LuChevronDown } from "react-icons/lu" const Demo = () => { return ( <Group attached> <Button variant="outline" size="sm"> Button </Button> <IconButton variant="outline" size="sm"> <LuChevronDown /> </IconButton> </Group> ) } ``` ## [Props]() PropDefaultType`colorPalette``'gray'` `'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink' | 'accent'` The color palette of the component `size``'md'` `'xs' | 'sm' | 'md' | 'lg'` The size of the component `variant``'solid'` `'solid' | 'subtle' | 'surface' | 'outline' | 'ghost' | 'plain'` The variant of the component `loading` `boolean` `loadingText` `React.ReactNode` [Previous \ Breadcrumb](https://www.chakra-ui.com/docs/components/breadcrumb) [Next \ Card](https://www.chakra-ui.com/docs/components/card)
https://www.chakra-ui.com/docs/components/card
1. Components 2. Card # Card Used to display content related to a single subject. [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/card)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Fcomponents-card--basic)[Recipe](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/theme/recipes/card.ts) PreviewCode NC![](https://picsum.photos/200/300) ### Nue Camp This is the card body. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur nec odio vel dui euismod fermentum. Curabitur nec odio vel dui euismod fermentum. ViewJoin ``` import { Card } from "@chakra-ui/react" import { Avatar } from "@/components/ui/avatar" import { Button } from "@/components/ui/button" const Demo = () => { return ( <Card.Root width="320px"> <Card.Body gap="2"> <Avatar src="https://picsum.photos/200/300" name="Nue Camp" size="lg" shape="rounded" /> <Card.Title mt="2">Nue Camp</Card.Title> <Card.Description> This is the card body. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur nec odio vel dui euismod fermentum. Curabitur nec odio vel dui euismod fermentum. </Card.Description> </Card.Body> <Card.Footer justifyContent="flex-end"> <Button variant="outline">View</Button> <Button>Join</Button> </Card.Footer> </Card.Root> ) } ``` ## [Usage]() ``` import { Card } from "@chakra-ui/react" ``` ``` <Card.Root> <Card.Header /> <Card.Body /> <Card.Footer /> </Card.Root> ``` ## [Examples]() ### [Variants]() Use the `variant` prop to change the visual style of the Card. PreviewCode NC![](https://picsum.photos/200/300) ### Nue Camp This is the card body. Lorem ipsum dolor sit amet, consectetur adipiscing elit. ViewJoin NC![](https://picsum.photos/200/300) ### Nue Camp This is the card body. Lorem ipsum dolor sit amet, consectetur adipiscing elit. ViewJoin NC![](https://picsum.photos/200/300) ### Nue Camp This is the card body. Lorem ipsum dolor sit amet, consectetur adipiscing elit. ViewJoin ``` import { Card, For, Stack } from "@chakra-ui/react" import { Avatar } from "@/components/ui/avatar" import { Button } from "@/components/ui/button" const Demo = () => { return ( <Stack gap="4" direction="row" wrap="wrap"> <For each={["subtle", "outline", "elevated"]}> {(variant) => ( <Card.Root width="320px" variant={variant} key={variant}> <Card.Body gap="2"> <Avatar src="https://picsum.photos/200/300" name="Nue Camp" size="lg" shape="rounded" /> <Card.Title mb="2">Nue Camp</Card.Title> <Card.Description> This is the card body. Lorem ipsum dolor sit amet, consectetur adipiscing elit. </Card.Description> </Card.Body> <Card.Footer justifyContent="flex-end"> <Button variant="outline">View</Button> <Button>Join</Button> </Card.Footer> </Card.Root> )} </For> </Stack> ) } ``` ### [Within Form]() Use the Card component within a form to group related fields together. PreviewCode ### Sign up Fill in the form below to create an account First Name Last Name CancelSign in ``` import { Button, Card, Input, Stack } from "@chakra-ui/react" import { Field } from "@/components/ui/field" export const CardWithForm = () => ( <Card.Root maxW="sm"> <Card.Header> <Card.Title>Sign up</Card.Title> <Card.Description> Fill in the form below to create an account </Card.Description> </Card.Header> <Card.Body> <Stack gap="4" w="full"> <Field label="First Name"> <Input /> </Field> <Field label="Last Name"> <Input /> </Field> </Stack> </Card.Body> <Card.Footer justifyContent="flex-end"> <Button variant="outline">Cancel</Button> <Button variant="solid">Sign in</Button> </Card.Footer> </Card.Root> ) ``` ### [Sizes]() Use the `size` prop to change the size of the Card. PreviewCode ## Card - sm This is the card body. Lorem ipsum dolor sit amet, consectetur adipiscing elit. ## Card - md This is the card body. Lorem ipsum dolor sit amet, consectetur adipiscing elit. ## Card - lg This is the card body. Lorem ipsum dolor sit amet, consectetur adipiscing elit. ``` import { Card, Heading, Stack } from "@chakra-ui/react" const Demo = () => { return ( <Stack> <Card.Root size="sm"> <Card.Header> <Heading size="md"> Card - sm</Heading> </Card.Header> <Card.Body color="fg.muted"> This is the card body. Lorem ipsum dolor sit amet, consectetur adipiscing elit. </Card.Body> </Card.Root> <Card.Root size="md"> <Card.Header> <Heading size="md"> Card - md</Heading> </Card.Header> <Card.Body color="fg.muted"> This is the card body. Lorem ipsum dolor sit amet, consectetur adipiscing elit. </Card.Body> </Card.Root> <Card.Root size="lg"> <Card.Header> <Heading size="md"> Card - lg</Heading> </Card.Header> <Card.Body color="fg.muted"> This is the card body. Lorem ipsum dolor sit amet, consectetur adipiscing elit. </Card.Body> </Card.Root> </Stack> ) } ``` ### [With Image]() Use the Card component to display an image. PreviewCode ![Green double couch with wooden legs](https://images.unsplash.com/photo-1555041469-a586c61ea9bc?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1770&q=80) ### Living room Sofa This sofa is perfect for modern tropical spaces, baroque inspired spaces. $450 Buy nowAdd to cart ``` import { Button, Card, Image, Text } from "@chakra-ui/react" const Demo = () => { return ( <Card.Root maxW="sm" overflow="hidden"> <Image src="https://images.unsplash.com/photo-1555041469-a586c61ea9bc?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1770&q=80" alt="Green double couch with wooden legs" /> <Card.Body gap="2"> <Card.Title>Living room Sofa</Card.Title> <Card.Description> This sofa is perfect for modern tropical spaces, baroque inspired spaces. </Card.Description> <Text textStyle="2xl" fontWeight="medium" letterSpacing="tight" mt="2"> $450 </Text> </Card.Body> <Card.Footer gap="2"> <Button variant="solid">Buy now</Button> <Button variant="ghost">Add to cart</Button> </Card.Footer> </Card.Root> ) } ``` ### [Horizontal]() Use the Card component to display content horizontally. PreviewCode ![Caffe Latte](https://images.unsplash.com/photo-1667489022797-ab608913feeb?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw5fHx8ZW58MHx8fHw%3D&auto=format&fit=crop&w=800&q=60) ### The perfect latte Caffè latte is a coffee beverage of Italian origin made with espresso and steamed milk. HotCaffeine Buy Latte ``` import { Badge, Box, Card, HStack, Image } from "@chakra-ui/react" import { Button } from "@/components/ui/button" export const CardHorizontal = () => ( <Card.Root flexDirection="row" overflow="hidden" maxW="xl"> <Image objectFit="cover" maxW="200px" src="https://images.unsplash.com/photo-1667489022797-ab608913feeb?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw5fHx8ZW58MHx8fHw%3D&auto=format&fit=crop&w=800&q=60" alt="Caffe Latte" /> <Box> <Card.Body> <Card.Title mb="2">The perfect latte</Card.Title> <Card.Description> Caffè latte is a coffee beverage of Italian origin made with espresso and steamed milk. </Card.Description> <HStack mt="4"> <Badge>Hot</Badge> <Badge>Caffeine</Badge> </HStack> </Card.Body> <Card.Footer> <Button>Buy Latte</Button> </Card.Footer> </Box> </Card.Root> ) ``` ### [With Avatar]() Use the Card component to display an avatar. PreviewCode NF![](https://images.unsplash.com/photo-1511806754518-53bada35f930) Nate Foss @natefoss **Nate Foss** has requested to join your team. You can approve or decline their request. DeclineApprove ``` import { Card, HStack, Stack, Strong, Text } from "@chakra-ui/react" import { Avatar } from "@/components/ui/avatar" import { Button } from "@/components/ui/button" import { LuCheck, LuX } from "react-icons/lu" const Demo = () => { return ( <Card.Root width="320px"> <Card.Body> <HStack mb="6" gap="3"> <Avatar src="https://images.unsplash.com/photo-1511806754518-53bada35f930" name="Nate Foss" /> <Stack gap="0"> <Text fontWeight="semibold" textStyle="sm"> Nate Foss </Text> <Text color="fg.muted" textStyle="sm"> @natefoss </Text> </Stack> </HStack> <Card.Description> <Strong color="fg">Nate Foss </Strong> has requested to join your team. You can approve or decline their request. </Card.Description> </Card.Body> <Card.Footer> <Button variant="subtle" colorPalette="red" flex="1"> <LuX /> Decline </Button> <Button variant="subtle" colorPalette="blue" flex="1"> <LuCheck /> Approve </Button> </Card.Footer> </Card.Root> ) } ``` ## [Props]() ### [Root]() PropDefaultType`colorPalette``'gray'` `'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink' | 'accent'` The color palette of the component `size``'md'` `'sm' | 'md' | 'lg'` The size of the component `variant``'outline'` `'elevated' | 'outline' | 'subtle'` The variant of the component [Previous \ Button](https://www.chakra-ui.com/docs/components/button) [Next \ Checkbox Card](https://www.chakra-ui.com/docs/components/checkbox-card)
https://www.chakra-ui.com/docs/components/checkbox-card
1. Components 2. Checkbox Card # Checkbox Card Used to select or deselect options displayed within cards. [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/checkbox-card)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Fcomponents-checkbox-card--basic)[Recipe](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/theme/recipes/checkbox-card.ts)[Ark](https://ark-ui.com/react/docs/components/checkbox) PreviewCode Next.js Best for apps ``` import { CheckboxCard } from "@/components/ui/checkbox-card" const Demo = () => { return ( <CheckboxCard label="Next.js" description="Best for apps" maxW="240px" /> ) } ``` ## [Setup]() If you don't already have the snippet, run the following command to add the `checkbox-card` snippet ``` npx @chakra-ui/cli snippet add checkbox-card ``` The snippet includes a closed component composition for the `CheckboxCard` component. ## [Usage]() ``` import { CheckboxCard } from "@/components/ui/checkbox-card" ``` ``` <CheckboxCard label="Checkbox Card" /> ``` ## [Examples]() ### [Group]() Use the `CheckboxCardGroup` component to group multiple checkbox cards. PreviewCode Select framework(s) Next.js Best for apps Vite Best for SPAs Astro Best for static sites ``` import { CheckboxGroup, Flex, Text } from "@chakra-ui/react" import { CheckboxCard } from "@/components/ui/checkbox-card" const Demo = () => { return ( <CheckboxGroup defaultValue={["next"]}> <Text textStyle="sm" fontWeight="medium"> Select framework(s) </Text> <Flex gap="2"> {items.map((item) => ( <CheckboxCard label={item.title} description={item.description} key={item.value} value={item.value} /> ))} </Flex> </CheckboxGroup> ) } const items = [ { value: "next", title: "Next.js", description: "Best for apps" }, { value: "vite", title: "Vite", description: "Best for SPAs" }, { value: "astro", title: "Astro", description: "Best for static sites" }, ] ``` ### [Sizes]() Use the `size` prop to change the size of the checkbox card. PreviewCode Checkbox (sm) Checkbox (md) Checkbox (lg) ``` import { For, Stack } from "@chakra-ui/react" import { CheckboxCard } from "@/components/ui/checkbox-card" const Demo = () => { return ( <Stack maxW="320px"> <For each={["sm", "md", "lg"]}> {(size) => <CheckboxCard label={`Checkbox (${size})`} size={size} />} </For> </Stack> ) } ``` ### [Variants]() Use the `variant` prop to change the variant of the checkbox card. PreviewCode Checkbox (subtle) Checkbox (surface) Checkbox (outline) ``` import { For, Stack } from "@chakra-ui/react" import { CheckboxCard } from "@/components/ui/checkbox-card" const Demo = () => { return ( <Stack maxW="320px"> <For each={["subtle", "surface", "outline"]}> {(variant) => ( <CheckboxCard defaultChecked label={`Checkbox (${variant})`} colorPalette="teal" variant={variant} /> )} </For> </Stack> ) } ``` ### [Disabled]() Use the `disabled` prop to make the checkbox card disabled. PreviewCode Disabled This is a disabled checkbox ``` import { CheckboxCard } from "@/components/ui/checkbox-card" const Demo = () => { return ( <CheckboxCard disabled label="Disabled" description="This is a disabled checkbox" maxW="320px" /> ) } ``` ### [Addon]() Use the `CheckboxCardAddon` to add some more context to the checkbox card. PreviewCode With Addon Some description Some supporting textNew ``` import { Badge, HStack } from "@chakra-ui/react" import { CheckboxCard } from "@/components/ui/checkbox-card" const Demo = () => { return ( <CheckboxCard label="With Addon" description="Some description" maxW="300px" addon={ <HStack> Some supporting text <Badge variant="solid">New</Badge> </HStack> } /> ) } ``` ### [Icon]() Render custom icons within the checkbox card. PreviewCode Admin Give full access User Give limited access Guest Give read-only access Blocked No access ``` import { CheckboxGroup, Float, Icon, SimpleGrid } from "@chakra-ui/react" import { CheckboxCard, CheckboxCardIndicator, } from "@/components/ui/checkbox-card" import { HiGlobeAlt, HiLockClosed, HiShieldCheck, HiUser } from "react-icons/hi" const Demo = () => { return ( <CheckboxGroup defaultValue={["Guest"]}> <SimpleGrid minChildWidth="200px" gap="2"> {items.map((item) => ( <CheckboxCard align="center" key={item.label} icon={ <Icon fontSize="2xl" mb="2"> {item.icon} </Icon> } label={item.label} description={item.description} indicator={ <Float placement="top-end" offset="6"> <CheckboxCardIndicator /> </Float> } /> ))} </SimpleGrid> </CheckboxGroup> ) } const items = [ { icon: <HiShieldCheck />, label: "Admin", description: "Give full access" }, { icon: <HiUser />, label: "User", description: "Give limited access" }, { icon: <HiGlobeAlt />, label: "Guest", description: "Give read-only access", }, { icon: <HiLockClosed />, label: "Blocked", description: "No access" }, ] ``` ### [Without Snippet]() If you don't want to use the snippet, you can use the `CheckboxCard` component from the `@chakra-ui/react` package. PreviewCode Next.js Best for apps ``` import { CheckboxCard } from "@chakra-ui/react" const Demo = () => { return ( <CheckboxCard.Root maxW="240px"> <CheckboxCard.HiddenInput /> <CheckboxCard.Control> <CheckboxCard.Indicator /> </CheckboxCard.Control> <CheckboxCard.Content> <CheckboxCard.Label>Next.js</CheckboxCard.Label> <CheckboxCard.Description>Best for apps</CheckboxCard.Description> </CheckboxCard.Content> </CheckboxCard.Root> ) } ``` ## [Props]() ### [Root]() PropDefaultType`colorPalette``'gray'` `'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink' | 'accent'` The color palette of the component `size``'md'` `'sm' | 'md' | 'lg'` The size of the component `variant``'outline'` `'plain' | 'subtle' | 'outline'` The variant of the component `as` `React.ElementType` The underlying element to render. `asChild` `boolean` Use the provided child element as the default rendered element, combining their props and behavior. For more details, read our [Composition](https://www.chakra-ui.com/docs/guides/composition) guide. `unstyled` `boolean` Whether to remove the component's style. [Previous \ Card](https://www.chakra-ui.com/docs/components/card) [Next \ Checkbox](https://www.chakra-ui.com/docs/components/checkbox)
https://www.chakra-ui.com/docs/components/clipboard
1. Components 2. Clipboard # Clipboard Used to copy text to the clipboard [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/clipboard)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Fcomponents-clipboard--basic)[Recipe](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/theme/recipes/clipboard.ts)[Ark](https://ark-ui.com/react/docs/components/clipboard) PreviewCode Copy ``` import { ClipboardIconButton, ClipboardRoot } from "@/components/ui/clipboard" const Demo = () => { return ( <ClipboardRoot value="https://chakra-ui.com"> <ClipboardIconButton /> </ClipboardRoot> ) } ``` ## [Setup]() If you don't already have the snippet, run the following command to add the `clipboard` snippet ``` npx @chakra-ui/cli snippet add clipboard ``` The snippet includes a closed component composition for the `Clipboard` component. ## [Usage]() ``` import { ClipboardButton, ClipboardIconButton, ClipboardInput, } from "@/components/ui/clipboard" ``` ``` <ClipboardRoot value="..."> <ClipboardButton /> <ClipboardIconButton /> <ClipboardInput /> </ClipboardRoot> ``` ## [Examples]() ### [Copy Button]() Use the `Clipboard.Context` and `Clipboard.Trigger` components to create a copy button. PreviewCode Copy ``` import { ClipboardButton, ClipboardRoot } from "@/components/ui/clipboard" const Demo = () => { return ( <ClipboardRoot value="https://chakra-ui.com"> <ClipboardButton /> </ClipboardRoot> ) } ``` ### [Input]() Use the `Clipboard.Input` component to create a copy input. PreviewCode Document Link Copy ``` import { ClipboardIconButton, ClipboardInput, ClipboardLabel, ClipboardRoot, } from "@/components/ui/clipboard" import { InputGroup } from "@/components/ui/input-group" const Demo = () => { return ( <ClipboardRoot maxW="300px" value="https://sharechakra-ui.com/dfr3def"> <ClipboardLabel>Document Link</ClipboardLabel> <InputGroup width="full" endElement={<ClipboardIconButton me="-2" />}> <ClipboardInput /> </InputGroup> </ClipboardRoot> ) } ``` ### [Timeout]() Use the `timeout` prop to change the duration of the copy message. PreviewCode Copy ``` import { ClipboardButton, ClipboardRoot } from "@/components/ui/clipboard" const Demo = () => { return ( <ClipboardRoot value="https://chakra-ui.com" timeout={1000}> <ClipboardButton /> </ClipboardRoot> ) } ``` ### [Link Appearance]() Use the `ClipboardText` component to create a link appearance. PreviewCode Copy ``` "use client" import { ClipboardLink, ClipboardRoot } from "@/components/ui/clipboard" const Demo = () => { return ( <ClipboardRoot value="https://chakra-ui.com"> <ClipboardLink color="blue.fg" textStyle="sm" /> </ClipboardRoot> ) } ``` ### [Without Snippet]() If you don't want to use the snippet, you can use the `Clipboard` component from the `@chakra-ui/react` package. PreviewCode ``` import { Clipboard, IconButton } from "@chakra-ui/react" import { LuClipboard } from "react-icons/lu" import { LuCheck } from "react-icons/lu" const Demo = () => { return ( <Clipboard.Root value="https://chakra-ui.com"> <Clipboard.Trigger asChild> <IconButton> <Clipboard.Indicator copied={<LuCheck />}> <LuClipboard /> </Clipboard.Indicator> </IconButton> </Clipboard.Trigger> </Clipboard.Root> ) } ``` ## [Props]() ### [Root]() PropDefaultType`timeout``'3000'` `number` The timeout for the copy operation `asChild` `boolean` Use the provided child element as the default rendered element, combining their props and behavior. For more details, read our [Composition](https://www.chakra-ui.com/docs/guides/composition) guide. `ids` `Partial<{ root: string; input: string; label: string }>` The ids of the elements in the clipboard. Useful for composition. `onStatusChange` `(details: CopyStatusDetails) => void` The function to be called when the value is copied to the clipboard `value` `string` The value to be copied to the clipboard [Previous \ Checkbox](https://www.chakra-ui.com/docs/components/checkbox) [Next \ Close Button](https://www.chakra-ui.com/docs/components/close-button)
https://www.chakra-ui.com/docs/components/collapsible
1. Components 2. Collapsible # Collapsible Used to expand and collapse additional content. [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/collapsible)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Fcomponents-collapsible--basic)[Recipe](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/theme/recipes/collapsible.ts)[Ark](https://ark-ui.com/react/docs/components/collapsible) PreviewCode Toggle Collapsible Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. ``` import { Box, Collapsible } from "@chakra-ui/react" export const CollapsibleBasic = () => ( <Collapsible.Root> <Collapsible.Trigger paddingY="3">Toggle Collapsible</Collapsible.Trigger> <Collapsible.Content> <Box padding="4" borderWidth="1px"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. </Box> </Collapsible.Content> </Collapsible.Root> ) ``` ## [Usage]() ``` import { Collapsible } from "@chakra-ui/react" ``` ``` <Collapsible.Root> <Collapsible.Trigger /> <Collapsible.Content /> </Collapsible.Root> ``` ## [Examples]() ### [Lazy Mounted]() Use the `unmountOnExit` prop to make the content unmount when collapsed. PreviewCode Toggle Collapse (Unmount on exit) If you inspect the DOM, you'll notice that the content is unmounted when collapsed. This is useful for performance reasons when you have a lot of collapsible content. ``` import { Box, Collapsible } from "@chakra-ui/react" export const CollapsibleLazyMounted = () => ( <Collapsible.Root unmountOnExit> <Collapsible.Trigger paddingY="3"> Toggle Collapse (Unmount on exit) </Collapsible.Trigger> <Collapsible.Content> <Box padding="4" borderWidth="1px"> If you inspect the DOM, you'll notice that the content is unmounted when collapsed. This is useful for performance reasons when you have a lot of collapsible content. </Box> </Collapsible.Content> </Collapsible.Root> ) ``` ## [Props]() ### [Root]() PropDefaultType`lazyMount``false` `boolean` Whether to enable lazy mounting `unmountOnExit``false` `boolean` Whether to unmount on exit. `asChild` `boolean` Use the provided child element as the default rendered element, combining their props and behavior. For more details, read our [Composition](https://www.chakra-ui.com/docs/guides/composition) guide. `defaultOpen` `boolean` The initial open state of the collapsible when it is first rendered. Use when you do not need to control its open state. `disabled` `boolean` Whether the collapsible is disabled `ids` `Partial<{ root: string; content: string; trigger: string }>` The ids of the elements in the collapsible. Useful for composition. `onExitComplete` `() => void` Function called when the animation ends in the closed state. `onOpenChange` `(details: OpenChangeDetails) => void` Function called when the popup is opened `open` `boolean` Whether the collapsible is open [Previous \ Close Button](https://www.chakra-ui.com/docs/components/close-button) [Next \ Color Picker](https://www.chakra-ui.com/docs/components/color-picker)
https://www.chakra-ui.com/docs/components/checkbox
1. Components 2. Checkbox # Checkbox Used in forms when a user needs to select multiple values from several options [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/checkbox)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Fcomponents-checkbox--basic)[Recipe](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/theme/recipes/checkbox.ts)[Ark](https://ark-ui.com/react/docs/components/checkbox) PreviewCode Accept terms and conditions ``` import { Checkbox } from "@/components/ui/checkbox" const Demo = () => { return <Checkbox>Accept terms and conditions</Checkbox> } ``` ## [Setup]() If you don't already have the snippet, run the following command to add the `checkbox` snippet ``` npx @chakra-ui/cli snippet add checkbox ``` The snippet includes a closed component composition for the `Checkbox` ## [Usage]() ``` import { Checkbox } from "@/components/ui/checkbox" ``` ``` <Checkbox>Click me</Checkbox> ``` ## [Examples]() ### [Variants]() Use the `variant` prop to change the visual style of the checkbox. PreviewCode outline Checkbox subtle Checkbox solid Checkbox ``` import { For, HStack, Stack, Text } from "@chakra-ui/react" import { Checkbox } from "@/components/ui/checkbox" const Demo = () => { return ( <HStack align="flex-start"> <For each={["outline", "subtle", "solid"]}> {(variant) => ( <Stack align="flex-start" flex="1" key={variant}> <Text>{variant}</Text> <Checkbox defaultChecked variant={variant}> Checkbox </Checkbox> </Stack> )} </For> </HStack> ) } ``` ### [Controlled]() Use the `checked` and `onCheckedChange` props to control the state of the checkbox. PreviewCode Accept terms and conditions ``` "use client" import { Checkbox } from "@/components/ui/checkbox" import { useState } from "react" const Demo = () => { const [checked, setChecked] = useState(false) return ( <Checkbox checked={checked} onCheckedChange={(e) => setChecked(!!e.checked)} > Accept terms and conditions </Checkbox> ) } ``` ### [Colors]() Use the `colorPalette` prop to change the color of the checkbox. PreviewCode gray Checkbox Checkbox Checkbox Checkbox Checkbox Checkbox red Checkbox Checkbox Checkbox Checkbox Checkbox Checkbox green Checkbox Checkbox Checkbox Checkbox Checkbox Checkbox blue Checkbox Checkbox Checkbox Checkbox Checkbox Checkbox teal Checkbox Checkbox Checkbox Checkbox Checkbox Checkbox pink Checkbox Checkbox Checkbox Checkbox Checkbox Checkbox purple Checkbox Checkbox Checkbox Checkbox Checkbox Checkbox cyan Checkbox Checkbox Checkbox Checkbox Checkbox Checkbox orange Checkbox Checkbox Checkbox Checkbox Checkbox Checkbox yellow Checkbox Checkbox Checkbox Checkbox Checkbox Checkbox ``` import { For, Stack, Text } from "@chakra-ui/react" import { colorPalettes } from "compositions/lib/color-palettes" import { Checkbox } from "@/components/ui/checkbox" const Demo = () => { return ( <Stack gap="2" align="flex-start"> {colorPalettes.map((colorPalette) => ( <Stack align="center" key={colorPalette} direction="row" gap="10" width="full" > <Text minW="8ch">{colorPalette}</Text> <For each={["outline", "subtle", "solid"]}> {(variant) => ( <Stack key={variant} mb="4"> <Checkbox variant={variant} colorPalette={colorPalette}> Checkbox </Checkbox> <Checkbox defaultChecked variant={variant} colorPalette={colorPalette} > Checkbox </Checkbox> </Stack> )} </For> </Stack> ))} </Stack> ) } ``` ### [Sizes]() Use the `size` prop to change the size of the checkbox. PreviewCode Checkbox Checkbox Checkbox ``` import { For, Stack } from "@chakra-ui/react" import { Checkbox } from "@/components/ui/checkbox" const Demo = () => { return ( <Stack align="flex-start" flex="1" gap="4"> <For each={["sm", "md", "lg"]}> {(size) => ( <Checkbox defaultChecked size={size} key={size}> Checkbox </Checkbox> )} </For> </Stack> ) } ``` ### [States]() Use the `disabled` or `invalid` prop to change the visual state of the checkbox. PreviewCode Disabled Disabled Readonly Invalid ``` import { Stack } from "@chakra-ui/react" import { Checkbox } from "@/components/ui/checkbox" const Demo = () => { return ( <Stack> <Checkbox disabled>Disabled</Checkbox> <Checkbox defaultChecked disabled> Disabled </Checkbox> <Checkbox readOnly>Readonly</Checkbox> <Checkbox invalid>Invalid</Checkbox> </Stack> ) } ``` ### [Hook Form]() Here's an example of how to use the `Checkbox` component with the `react-hook-form` library. PreviewCode Checkbox ToggleReset Submit`Checked: false` ``` "use client" import { Button, Code, HStack, Stack } from "@chakra-ui/react" import { zodResolver } from "@hookform/resolvers/zod" import { Checkbox } from "@/components/ui/checkbox" import { Field } from "@/components/ui/field" import { Controller, useController, useForm } from "react-hook-form" import { z } from "zod" const formSchema = z.object({ enabled: z.boolean(), }) type FormData = z.infer<typeof formSchema> const Demo = () => { const form = useForm<FormData>({ resolver: zodResolver(formSchema), defaultValues: { enabled: false }, }) const enabled = useController({ control: form.control, name: "enabled", }) const invalid = !!form.formState.errors.enabled return ( <form onSubmit={form.handleSubmit((data) => console.log(data))}> <Stack align="flex-start"> <Controller control={form.control} name="enabled" render={({ field }) => ( <Field disabled={field.disabled} invalid={invalid} errorText={form.formState.errors.enabled?.message} > <Checkbox checked={field.value} onCheckedChange={({ checked }) => field.onChange(checked)} > Checkbox </Checkbox> </Field> )} /> <HStack> <Button size="xs" variant="outline" onClick={() => form.setValue("enabled", !enabled.field.value)} > Toggle </Button> <Button size="xs" variant="outline" onClick={() => form.reset()}> Reset </Button> </HStack> <Button size="sm" type="submit" alignSelf="flex-start"> Submit </Button> <Code>Checked: {JSON.stringify(enabled.field.value, null, 2)}</Code> </Stack> </form> ) } ``` ### [Group]() Use the `CheckboxGroup` component to group multiple checkboxes together. PreviewCode Select framework React Svelte Vue Angular ``` import { CheckboxGroup, Fieldset } from "@chakra-ui/react" import { Checkbox } from "@/components/ui/checkbox" const Demo = () => { return ( <Fieldset.Root> <CheckboxGroup defaultValue={["react"]} name="framework"> <Fieldset.Legend fontSize="sm" mb="2"> Select framework </Fieldset.Legend> <Fieldset.Content> <Checkbox value="react">React</Checkbox> <Checkbox value="svelte">Svelte</Checkbox> <Checkbox value="vue">Vue</Checkbox> <Checkbox value="angular">Angular</Checkbox> </Fieldset.Content> </CheckboxGroup> </Fieldset.Root> ) } ``` ### [Group Hook Form]() Here's an example of how to use the `CheckboxGroup` component with the `react-hook-form` library. PreviewCode Select your framework React Svelte Vue Angular Submit`Values: []` ``` "use client" import { Button, CheckboxGroup, Code, Fieldset } from "@chakra-ui/react" import { zodResolver } from "@hookform/resolvers/zod" import { Checkbox } from "@/components/ui/checkbox" import { useController, useForm } from "react-hook-form" import { z } from "zod" const formSchema = z.object({ framework: z.array(z.string()).min(1, { message: "You must select at least one framework.", }), }) type FormData = z.infer<typeof formSchema> const items = [ { label: "React", value: "react" }, { label: "Svelte", value: "svelte" }, { label: "Vue", value: "vue" }, { label: "Angular", value: "angular" }, ] const Demo = () => { const { handleSubmit, control, formState: { errors }, } = useForm<FormData>({ resolver: zodResolver(formSchema), }) const framework = useController({ control, name: "framework", defaultValue: [], }) const invalid = !!errors.framework return ( <form onSubmit={handleSubmit((data) => console.log(data))}> <Fieldset.Root invalid={invalid}> <Fieldset.Legend>Select your framework</Fieldset.Legend> <CheckboxGroup invalid={invalid} value={framework.field.value} onValueChange={framework.field.onChange} name={framework.field.name} > <Fieldset.Content> {items.map((item) => ( <Checkbox key={item.value} value={item.value}> {item.label} </Checkbox> ))} </Fieldset.Content> </CheckboxGroup> {errors.framework && ( <Fieldset.ErrorText>{errors.framework.message}</Fieldset.ErrorText> )} <Button size="sm" type="submit" alignSelf="flex-start"> Submit </Button> <Code>Values: {JSON.stringify(framework.field.value, null, 2)}</Code> </Fieldset.Root> </form> ) } ``` ### [Custom Icon]() Use the `icon` prop to change the icon of the checkbox. PreviewCode With Custom Icon ``` import { Checkbox } from "@/components/ui/checkbox" import { HiOutlinePlus } from "react-icons/hi" const Demo = () => { return ( <Checkbox defaultChecked icon={<HiOutlinePlus />}> With Custom Icon </Checkbox> ) } ``` ### [Indeterminate]() Set the `checked` prop to `indeterminate` to show the checkbox in an indeterminate state. PreviewCode Weekdays Monday Tuesday Wednesday Thursday ``` "use client" import { Stack } from "@chakra-ui/react" import { Checkbox } from "@/components/ui/checkbox" import { useState } from "react" const initialValues = [ { label: "Monday", checked: false, value: "monday" }, { label: "Tuesday", checked: false, value: "tuesday" }, { label: "Wednesday", checked: false, value: "wednesday" }, { label: "Thursday", checked: false, value: "thursday" }, ] const Demo = () => { const [values, setValues] = useState(initialValues) const allChecked = values.every((value) => value.checked) const indeterminate = values.some((value) => value.checked) && !allChecked const items = values.map((item, index) => ( <Checkbox ms="6" key={item.value} checked={item.checked} onCheckedChange={(e) => { setValues((current) => { const newValues = [...current] newValues[index] = { ...newValues[index], checked: !!e.checked } return newValues }) }} > {item.label} </Checkbox> )) return ( <Stack align="flex-start"> <Checkbox checked={indeterminate ? "indeterminate" : allChecked} onCheckedChange={(e) => { setValues((current) => current.map((value) => ({ ...value, checked: !!e.checked })), ) }} > Weekdays </Checkbox> {items} </Stack> ) } ``` ### [Description]() Add content to the children of the `Checkbox` component to add a description. PreviewCode I agree to the terms and conditions By clicking this, you agree to our Terms and Privacy Policy. ``` import { Box } from "@chakra-ui/react" import { Checkbox } from "@/components/ui/checkbox" const Demo = () => { return ( <Checkbox gap="4" alignItems="flex-start"> <Box lineHeight="1">I agree to the terms and conditions</Box> <Box fontWeight="normal" color="fg.muted" mt="1"> By clicking this, you agree to our Terms and Privacy Policy. </Box> </Checkbox> ) } ``` ### [Link]() Render an anchor tag as the checkbox label. PreviewCode I agree to the [terms and conditions](https://google.com) ``` import { Link } from "@chakra-ui/react" import { Checkbox } from "@/components/ui/checkbox" const Demo = () => { return ( <Checkbox> I agree to the{" "} <Link colorPalette="teal" href="https://google.com"> terms and conditions </Link> </Checkbox> ) } ``` ### [Without Snippet]() If you don't want to use the snippet, you can use the `Checkbox` component from the `@chakra-ui/react` package. PreviewCode Accept terms and conditions ``` import { Checkbox } from "@chakra-ui/react" const Demo = () => { return ( <Checkbox.Root> <Checkbox.HiddenInput /> <Checkbox.Control> <Checkbox.Indicator /> </Checkbox.Control> <Checkbox.Label>Accept terms and conditions</Checkbox.Label> </Checkbox.Root> ) } ``` ## [Props]() ### [Root]() PropDefaultType`value``'\'on\''` `string` The value of checkbox input. Useful for form submission. `colorPalette``'gray'` `'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink' | 'accent'` The color palette of the component `size``'md'` `'sm' | 'md' | 'lg'` The size of the component `variant``'outline'` `'outline' | 'subtle'` The variant of the component `asChild` `boolean` Use the provided child element as the default rendered element, combining their props and behavior. For more details, read our [Composition](https://www.chakra-ui.com/docs/guides/composition) guide. `checked` `CheckedState` The checked state of the checkbox `defaultChecked` `CheckedState` The checked state of the checkbox when it is first rendered. Use this when you do not need to control the state of the checkbox. `disabled` `boolean` Whether the checkbox is disabled `form` `string` The id of the form that the checkbox belongs to. `id` `string` The unique identifier of the machine. `ids` `Partial<{ root: string hiddenInput: string control: string label: string }>` The ids of the elements in the checkbox. Useful for composition. `invalid` `boolean` Whether the checkbox is invalid `name` `string` The name of the input field in a checkbox. Useful for form submission. `onCheckedChange` `(details: CheckedChangeDetails) => void` The callback invoked when the checked state changes. `readOnly` `boolean` Whether the checkbox is read-only `required` `boolean` Whether the checkbox is required `as` `React.ElementType` The underlying element to render. `unstyled` `boolean` Whether to remove the component's style. [Previous \ Checkbox Card](https://www.chakra-ui.com/docs/components/checkbox-card) [Next \ Clipboard](https://www.chakra-ui.com/docs/components/clipboard)
https://www.chakra-ui.com/docs/components/close-button
1. Components 2. Close Button # Close Button Used to trigger close functionality [Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Fcomponents-close-button--basic)[Recipe](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/theme/recipes/close-button.ts) PreviewCode ``` import { CloseButton } from "@/components/ui/close-button" const Demo = () => { return <CloseButton /> } ``` ## [Setup]() If you don't already have the snippet, run the following command to add the `close-button` snippet ``` npx @chakra-ui/cli snippet add close-button ``` The snippet includes a `CloseButton` component composition based on the `IconButton` component. ## [Usage]() ``` import { CloseButton } from "@/components/ui/close-button" ``` ``` <CloseButton /> ``` ## [Examples]() ### [Sizes]() Use the `size` prop to change the size of the close button. PreviewCode ``` import { For, HStack } from "@chakra-ui/react" import { CloseButton } from "@/components/ui/close-button" const Demo = () => { return ( <HStack gap="4" wrap="wrap"> <For each={["2xs", "xs", "sm", "md", "lg", "xl"]}> {(size) => <CloseButton variant="outline" size={size} />} </For> </HStack> ) } ``` ### [Variants]() Use the `variant` prop to change the appearance of the close button. PreviewCode ``` import { HStack } from "@chakra-ui/react" import { CloseButton } from "@/components/ui/close-button" const Demo = () => { return ( <HStack> <CloseButton variant="ghost" /> <CloseButton variant="outline" /> <CloseButton variant="subtle" /> <CloseButton variant="solid" /> </HStack> ) } ``` ### [Without Snippet]() If you don't want to use the snippet, you can use the `IconButton` component from the `@chakra-ui/react` package. PreviewCode ``` import { IconButton } from "@chakra-ui/react" import { LuX } from "react-icons/lu" const Demo = () => { return ( <IconButton variant="ghost" aria-label="Close"> <LuX /> </IconButton> ) } ``` ## [Props]() PropDefaultType`colorPalette``'gray'` `'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink' | 'accent'` The color palette of the component `size``'md'` `'xs' | 'sm' | 'md' | 'lg'` The size of the component `variant``'solid'` `'solid' | 'subtle' | 'surface' | 'outline' | 'ghost' | 'plain'` The variant of the component `loading` `boolean` `loadingText` `React.ReactNode` [Previous \ Clipboard](https://www.chakra-ui.com/docs/components/clipboard) [Next \ Collapsible](https://www.chakra-ui.com/docs/components/collapsible)
https://www.chakra-ui.com/docs/components/color-swatch
1. Components 2. Color Swatch # Color Swatch Used to preview a color [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/color-swatch)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Fcomponents-color-swatch--basic)[Recipe](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/theme/recipes/color-swatch.ts) PreviewCode ``` import { ColorSwatch } from "@chakra-ui/react" const Demo = () => { return <ColorSwatch value="#bada55" /> } ``` ## [Usage]() ``` import { ColorSwatch } from "@/components/ui/color-swatch" ``` ``` <ColorSwatch /> ``` ## [Examples]() ### [Sizes]() Use the `size` prop to change the size of the color swatch. PreviewCode ``` import { HStack } from "@chakra-ui/react" import { ColorSwatch } from "@chakra-ui/react" import { For } from "@chakra-ui/react" const Demo = () => { return ( <HStack> <For each={["2xs", "xs", "sm", "md", "lg", "xl", "2xl"]}> {(size) => <ColorSwatch key={size} value="#bada55" size={size} />} </For> </HStack> ) } ``` ### [Alpha]() Here's an example of how to create a color swatch with an alpha channel. PreviewCode ``` import { ColorSwatch, HStack } from "@chakra-ui/react" const Demo = () => { return ( <HStack> {colors.map((color) => ( <ColorSwatch key={color} value={color} size="xl" /> ))} </HStack> ) } const colors = [ "rgba(255, 0, 0, 0.5)", "rgba(0, 0, 255, 0.7)", "rgba(0, 255, 0, 0.4)", "rgba(255, 192, 203, 0.6)", ] ``` ### [With Badge]() Here's an example of how to compose the `ColorSwatch` with a `Badge`. PreviewCode #bada55 ``` import { Badge, ColorSwatch } from "@chakra-ui/react" const Demo = () => { return ( <Badge> <ColorSwatch value="#bada55" boxSize="0.82em" /> #bada55 </Badge> ) } ``` ### [Mixed Colors]() Use the `ColorSwatchMix` to create a color swatch that contains multiple colors, but retains the size of a single color swatch. PreviewCode ``` import { ColorSwatchMix, HStack } from "@chakra-ui/react" const Demo = () => { return ( <HStack> <ColorSwatchMix size="lg" items={["red", "pink"]} /> <ColorSwatchMix size="lg" items={["red", "pink", "green"]} /> <ColorSwatchMix size="lg" items={["lightgreen", "green", "darkgreen", "black"]} /> </HStack> ) } ``` ### [Palette]() Here's an example of composing multiple swatches to create a palette. PreviewCode ``` import { ColorSwatch, Group } from "@chakra-ui/react" const Demo = () => { return ( <Group attached width="full" maxW="sm" grow> {swatches.map((color) => ( <ColorSwatch key={color} value={color} size="2xl" /> ))} </Group> ) } const swatches = ["#ff0000", "#00ff00", "#0000ff", "#ffff00", "#ff00ff"] ``` [Previous \ Color Picker](https://www.chakra-ui.com/docs/components/color-picker) [Next \ Data List](https://www.chakra-ui.com/docs/components/data-list)
https://www.chakra-ui.com/docs/components/data-list
1. Components 2. Data List # DataList Used to display a list of similar data items. [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/data-list)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Fcomponents-data-list--basic)[Recipe](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/theme/recipes/data-list.ts) PreviewCode New Users 234 Sales £12,340 Revenue 3,450 ``` import { DataListItem, DataListRoot } from "@/components/ui/data-list" const stats = [ { label: "New Users", value: "234", diff: -12, helpText: "Till date" }, { label: "Sales", value: "£12,340", diff: 12, helpText: "Last 30 days" }, { label: "Revenue", value: "3,450", diff: 4.5, helpText: "Last 30 days" }, ] const Demo = () => { return ( <DataListRoot orientation="horizontal"> {stats.map((item) => ( <DataListItem key={item.label} label={item.label} value={item.value} /> ))} </DataListRoot> ) } ``` ## [Setup]() If you don't already have the snippet, run the following command to add the `data-list` snippet ``` npx @chakra-ui/cli snippet add data-list ``` The snippet includes a closed component composition for the `DataList` component. ## [Usage]() ``` import { DataListItem, DataListRoot } from "@/components/ui/data-list" ``` ``` <DataListRoot> {data.map((item) => ( <DataListItem key={item.label} label={item.label} value={item.value} /> ))} </DataListRoot> ``` ## [Examples]() ### [Sizes]() Use the `size` prop to change the size of the datalist component. PreviewCode Name John Doe Name John Doe Name John Doe ``` import { Stack } from "@chakra-ui/react" import { DataListItem, DataListRoot } from "@/components/ui/data-list" const Demo = () => { return ( <Stack gap="4"> <DataListRoot size="sm"> <DataListItem label="Name" value="John Doe" /> </DataListRoot> <DataListRoot size="md"> <DataListItem label="Name" value="John Doe" /> </DataListRoot> <DataListRoot size="lg"> <DataListItem label="Name" value="John Doe" /> </DataListRoot> </Stack> ) } ``` ### [Variants]() Use the `variant` prop to change the variant of the datalist component. Added in `v3.1.x` PreviewCode New Users 234 Sales £12,340 Revenue 3,450 New Users 234 Sales £12,340 Revenue 3,450 ``` import { For, Stack } from "@chakra-ui/react" import { DataListItem, DataListRoot } from "@/components/ui/data-list" const Demo = () => { return ( <Stack gap="8"> <For each={["subtle", "bold"]}> {(variant) => ( <DataListRoot variant={variant} key={variant}> {stats.map((item) => ( <DataListItem key={item.label} label={item.label} value={item.value} /> ))} </DataListRoot> )} </For> </Stack> ) } const stats = [ { label: "New Users", value: "234", diff: -12, helpText: "Till date" }, { label: "Sales", value: "£12,340", diff: 12, helpText: "Last 30 days" }, { label: "Revenue", value: "3,450", diff: 4.5, helpText: "Last 30 days" }, ] ``` ### [Orientation]() Use the `orientation` prop to change the orientation of the datalist component. PreviewCode New Users 234 Sales £12,340 Revenue 3,450 ``` import { DataListItem, DataListRoot } from "@/components/ui/data-list" const stats = [ { label: "New Users", value: "234", diff: -12, helpText: "Till date" }, { label: "Sales", value: "£12,340", diff: 12, helpText: "Last 30 days" }, { label: "Revenue", value: "3,450", diff: 4.5, helpText: "Last 30 days" }, ] const Demo = () => { return ( <DataListRoot> {stats.map((item) => ( <DataListItem key={item.label} label={item.label} value={item.value} /> ))} </DataListRoot> ) } ``` ### [Info Tip]() Use the `info` prop on the `DataListItem` to provide additional context to the datalist. PreviewCode New Users This is some info 234 Sales This is some info £12,340 Revenue This is some info 3,450 ``` import { DataListItem, DataListRoot } from "@/components/ui/data-list" const stats = [ { label: "New Users", value: "234", diff: -12, helpText: "Till date" }, { label: "Sales", value: "£12,340", diff: 12, helpText: "Last 30 days" }, { label: "Revenue", value: "3,450", diff: 4.5, helpText: "Last 30 days" }, ] const Demo = () => { return ( <DataListRoot orientation="horizontal"> {stats.map((item) => ( <DataListItem info="This is some info" key={item.label} label={item.label} value={item.value} /> ))} </DataListRoot> ) } ``` ### [Separator]() Use the `divideY` prop on the `DataListRoot` to add a separator between items. PreviewCode First Name Jassie Last Name Bhatia Email [email protected] Phone 1234567890 Address 1234 Main St, Anytown, USA ``` import { DataListItem } from "@/components/ui/data-list" import { DataListRoot } from "@/components/ui/data-list" const Demo = () => { return ( <DataListRoot orientation="horizontal" divideY="1px" maxW="md"> {items.map((item) => ( <DataListItem pt="4" grow key={item.value} label={item.label} value={item.value} /> ))} </DataListRoot> ) } const items = [ { label: "First Name", value: "Jassie" }, { label: "Last Name", value: "Bhatia" }, { label: "Email", value: "[email protected]" }, { label: "Phone", value: "1234567890" }, { label: "Address", value: "1234 Main St, Anytown, USA" }, ] ``` ## [Props]() ### [Root]() PropDefaultType`colorPalette``'gray'` `'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink' | 'accent'` The color palette of the component `orientation``'vertical'` `'horizontal' | 'vertical'` The orientation of the component `size``'md'` `'sm' | 'md' | 'lg'` The size of the component [Previous \ Color Swatch](https://www.chakra-ui.com/docs/components/color-swatch) [Next \ Dialog](https://www.chakra-ui.com/docs/components/dialog)
https://www.chakra-ui.com/docs/components/editable
1. Components 2. Editable # Editable Used for inline renaming of some text. [Source](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/components/editable)[Storybook](https://storybook.chakra-ui.com/?path=%2Fstory%2Fcomponents-editable--basic)[Recipe](https://github.com/chakra-ui/chakra-ui/tree/main/packages/react/src/theme/recipes/editable.ts)[Ark](https://ark-ui.com/react/docs/components/editable) PreviewCode Click to edit ``` import { Editable } from "@chakra-ui/react" export const EditableBasic = () => ( <Editable.Root textAlign="start" defaultValue="Click to edit"> <Editable.Preview /> <Editable.Input /> </Editable.Root> ) ``` ## [Usage]() ``` import { Editable } from "@chakra-ui/react" ``` ``` <Editable.Root> <Editable.Preview /> <Editable.Input /> </Editable.Root> ``` ## [Examples]() ### [Controlled]() PreviewCode Click to edit ``` "use client" import { Editable } from "@chakra-ui/react" import { useState } from "react" const Demo = () => { const [name, setName] = useState("") return ( <Editable.Root value={name} onValueChange={(e) => setName(e.value)} placeholder="Click to edit" > <Editable.Preview /> <Editable.Input /> </Editable.Root> ) } ``` ### [With Double Click]() Use the `activationMode` prop to make the content editable when users double click. PreviewCode Double click to edit ``` import { Editable } from "@chakra-ui/react" export const EditableWithDoubleClick = () => ( <Editable.Root defaultValue="Double click to edit" activationMode="dblclick"> <Editable.Preview /> <Editable.Input /> </Editable.Root> ) ``` ### [Disabled]() Use the `disabled` prop to disable the editable component. PreviewCode Click to edit ``` import { Editable } from "@chakra-ui/react" const Demo = () => { return ( <Editable.Root disabled defaultValue="Click to edit"> <Editable.Preview opacity={0.5} cursor="not-allowed" /> <Editable.Input /> </Editable.Root> ) } ``` ### [TextArea]() You can make a text area editable. PreviewCode Click to edit ``` import { Editable } from "@chakra-ui/react" const Demo = () => { return ( <Editable.Root defaultValue="Click to edit"> <Editable.Preview minH="48px" alignItems="flex-start" width="full" /> <Editable.Textarea /> </Editable.Root> ) } ``` ### [With Controls]() Add controls such as "edit", "cancel" and "submit" to `Editable` for better user experience. PreviewCode Click to edit ``` import { Editable, IconButton } from "@chakra-ui/react" import { LuCheck, LuPencilLine, LuX } from "react-icons/lu" const Demo = () => { return ( <Editable.Root defaultValue="Click to edit"> <Editable.Preview /> <Editable.Input /> <Editable.Control> <Editable.EditTrigger asChild> <IconButton variant="ghost" size="xs"> <LuPencilLine /> </IconButton> </Editable.EditTrigger> <Editable.CancelTrigger asChild> <IconButton variant="outline" size="xs"> <LuX /> </IconButton> </Editable.CancelTrigger> <Editable.SubmitTrigger asChild> <IconButton variant="outline" size="xs"> <LuCheck /> </IconButton> </Editable.SubmitTrigger> </Editable.Control> </Editable.Root> ) } ``` ## [Props]() ### [Root]() PropDefaultType`activationMode``'\'focus\''` `ActivationMode` The activation mode for the preview element. - "focus" - Enter edit mode when the preview is focused - "dblclick" - Enter edit mode when the preview is double-clicked - "click" - Enter edit mode when the preview is clicked `selectOnFocus``true` `boolean` Whether to select the text in the input when it is focused. `submitMode``'\'both\''` `SubmitMode` The action that triggers submit in the edit mode: - "enter" - Trigger submit when the enter key is pressed - "blur" - Trigger submit when the editable is blurred - "none" - No action will trigger submit. You need to use the submit button - "both" - Pressing \`Enter\` and blurring the input will trigger submit `asChild` `boolean` Use the provided child element as the default rendered element, combining their props and behavior. For more details, read our [Composition](https://www.chakra-ui.com/docs/guides/composition) guide. `autoResize` `boolean` Whether the editable should auto-resize to fit the content. `defaultEdit` `boolean` The initial edit state of the editable when it is first rendered. Use when you do not need to control its edit state. `defaultValue` `string` The initial value of the editable when it is first rendered. Use when you do not need to control the state of the editable. `disabled` `boolean` Whether the editable is disabled `edit` `boolean` Whether the editable is in edit mode. `finalFocusEl` `() => HTMLElement | null` The element that should receive focus when the editable is closed. By default, it will focus on the trigger element. `form` `string` The associate form of the underlying input. `id` `string` The unique identifier of the machine. `ids` `Partial<{ root: string area: string label: string preview: string input: string control: string submitTrigger: string cancelTrigger: string editTrigger: string }>` The ids of the elements in the editable. Useful for composition. `invalid` `boolean` Whether the input's value is invalid. `maxLength` `number` The maximum number of characters allowed in the editable `name` `string` The name attribute of the editable component. Used for form submission. `onEditChange` `(details: EditChangeDetails) => void` The callback that is called when the edit mode is changed `onFocusOutside` `(event: FocusOutsideEvent) => void` Function called when the focus is moved outside the component `onInteractOutside` `(event: InteractOutsideEvent) => void` Function called when an interaction happens outside the component `onPointerDownOutside` `(event: PointerDownOutsideEvent) => void` Function called when the pointer is pressed down outside the component `onValueChange` `(details: ValueChangeDetails) => void` The callback that is called when the editable's value is changed `onValueCommit` `(details: ValueChangeDetails) => void` The callback that is called when the editable's value is submitted. `onValueRevert` `(details: ValueChangeDetails) => void` The callback that is called when the esc key is pressed or the cancel button is clicked `placeholder` `string | { edit: string; preview: string }` The placeholder value to show when the \`value\` is empty `readOnly` `boolean` Whether the editable is readonly `required` `boolean` Whether the editable is required `translations` `IntlTranslations` Specifies the localized strings that identifies the accessibility elements and their states `value` `string` The value of the editable in both edit and preview mode [Previous \ Drawer](https://www.chakra-ui.com/docs/components/drawer) [Next \ Empty State](https://www.chakra-ui.com/docs/components/empty-state)