Aller au contenu

Chakra UI Cheat Sheet

Overview

Chakra UI is a component library for React that provides accessible, reusable, and composable building blocks for creating user interfaces. It follows WAI-ARIA standards, supports light and dark color modes out of the box, and uses a design token system for consistent styling. Components are styled using style props directly on elements, eliminating the need for external CSS.

Chakra UI is built on top of a styling system that maps CSS properties to short-hand props. It offers a theme-based approach where spacing, colors, typography, and breakpoints are defined centrally. The library includes over 60 components covering layout, forms, feedback, data display, navigation, and overlay patterns.

Installation

# Chakra UI v3 (latest)
npm install @chakra-ui/react @emotion/react

# Chakra UI v2 (legacy)
npm install @chakra-ui/react@2 @emotion/react @emotion/styled framer-motion

Setup

// main.tsx — Chakra v3
import { ChakraProvider, defaultSystem } from "@chakra-ui/react"

function App() {
  return (
    <ChakraProvider value={defaultSystem}>
      {/* Your app content */}
    </ChakraProvider>
  )
}

// main.tsx — Chakra v2
import { ChakraProvider } from "@chakra-ui/react"

function App() {
  return (
    <ChakraProvider>
      {/* Your app content */}
    </ChakraProvider>
  )
}

Core Components

Layout

import { Box, Flex, Stack, HStack, VStack, Grid, GridItem, Container, Center } from "@chakra-ui/react"

// Box — base building block
<Box p={4} bg="blue.500" color="white" borderRadius="md">
  Content
</Box>

// Flex layout
<Flex gap={4} align="center" justify="space-between">
  <Box>Left</Box>
  <Box>Right</Box>
</Flex>

// Stack (vertical by default)
<Stack spacing={4}>
  <Box>Item 1</Box>
  <Box>Item 2</Box>
</Stack>

// HStack (horizontal)
<HStack spacing={4}>
  <Button>One</Button>
  <Button>Two</Button>
</HStack>

// Grid
<Grid templateColumns="repeat(3, 1fr)" gap={6}>
  <GridItem colSpan={2} bg="blue.100" p={4}>Wide</GridItem>
  <GridItem bg="green.100" p={4}>Narrow</GridItem>
</Grid>

// Container with max width
<Container maxW="container.lg" py={8}>
  Centered content
</Container>

Typography and Data Display

import { Heading, Text, Badge, Tag, Code, Avatar, Card } from "@chakra-ui/react"

// Headings
<Heading as="h1" size="2xl">Main Title</Heading>
<Heading as="h2" size="lg">Section Title</Heading>

// Text
<Text fontSize="lg" color="gray.600">Body text</Text>
<Text noOfLines={2}>Truncated text after two lines...</Text>

// Badge
<Badge colorScheme="green">Active</Badge>
<Badge colorScheme="red" variant="solid">Critical</Badge>

// Tag
<Tag size="lg" colorScheme="blue">React</Tag>

// Code
<Code colorScheme="yellow">npm install chakra</Code>

// Avatar
<Avatar name="Alice Smith" src="/alice.jpg" size="lg" />

Form Components

import {
  Button, Input, Textarea, Select, Checkbox, Switch, Radio, RadioGroup,
  FormControl, FormLabel, FormHelperText, FormErrorMessage,
  NumberInput, NumberInputField, PinInput, PinInputField
} from "@chakra-ui/react"

// Input with form control
<FormControl isRequired isInvalid={!!error}>
  <FormLabel>Email</FormLabel>
  <Input type="email" placeholder="name@example.com" />
  {error ? (
    <FormErrorMessage>{error}</FormErrorMessage>
  ) : (
    <FormHelperText>We will never share your email.</FormHelperText>
  )}
</FormControl>

// Button variants
<Button colorScheme="blue">Primary</Button>
<Button colorScheme="gray" variant="outline">Secondary</Button>
<Button colorScheme="red" variant="ghost">Danger</Button>
<Button isLoading loadingText="Saving...">Save</Button>

// Select
<Select placeholder="Select role">
  <option value="admin">Admin</option>
  <option value="user">User</option>
</Select>

// Switch
<FormControl display="flex" alignItems="center">
  <FormLabel mb={0}>Dark Mode</FormLabel>
  <Switch colorScheme="blue" />
</FormControl>

// Radio Group
<RadioGroup defaultValue="1">
  <HStack spacing={4}>
    <Radio value="1">Option 1</Radio>
    <Radio value="2">Option 2</Radio>
    <Radio value="3">Option 3</Radio>
  </HStack>
</RadioGroup>

Feedback Components

import { Alert, AlertIcon, Spinner, Progress, Skeleton, Toast, useToast } from "@chakra-ui/react"

// Alert
<Alert status="success">
  <AlertIcon />
  Your account has been created!
</Alert>
<Alert status="error"><AlertIcon />Error occurred.</Alert>
<Alert status="warning"><AlertIcon />Caution advised.</Alert>
<Alert status="info"><AlertIcon />Tip: Try this feature.</Alert>

// Spinner
<Spinner size="xl" color="blue.500" />

// Progress
<Progress value={65} colorScheme="green" hasStripe isAnimated />

// Skeleton loading
<Skeleton height="20px" />
<Skeleton height="20px" width="80%" />

// Toast
function MyComponent() {
  const toast = useToast()
  return (
    <Button onClick={() =>
      toast({
        title: "Saved",
        description: "Your changes have been saved.",
        status: "success",
        duration: 3000,
        isClosable: true,
      })
    }>
      Save
    </Button>
  )
}

Style Props Reference

PropCSS PropertyExample
p / px / pypaddingp={4} = 16px
m / mx / mymarginm="auto"
w / hwidth / heightw="100%"
maxW / maxHmax-width / max-heightmaxW="container.lg"
bgbackgroundbg="blue.500"
colorcolorcolor="gray.700"
fontSizefont-sizefontSize="lg"
fontWeightfont-weightfontWeight="bold"
borderRadiusborder-radiusborderRadius="md"
shadowbox-shadowshadow="lg"
displaydisplaydisplay="flex"
positionpositionposition="relative"

Configuration

Custom Theme

import { extendTheme, ChakraProvider } from "@chakra-ui/react"

const theme = extendTheme({
  colors: {
    brand: {
      50: "#e6f2ff",
      100: "#b3d9ff",
      500: "#0066cc",
      600: "#0052a3",
      700: "#003d7a",
      900: "#001a33",
    },
  },
  fonts: {
    heading: "'Inter', sans-serif",
    body: "'Inter', sans-serif",
  },
  styles: {
    global: {
      body: {
        bg: "gray.50",
        color: "gray.800",
      },
    },
  },
  components: {
    Button: {
      defaultProps: {
        colorScheme: "brand",
      },
      variants: {
        primary: {
          bg: "brand.500",
          color: "white",
          _hover: { bg: "brand.600" },
        },
      },
    },
  },
})

<ChakraProvider theme={theme}>
  <App />
</ChakraProvider>

Responsive Styles

// Array syntax (mobile-first breakpoints: base, sm, md, lg, xl)
<Box fontSize={["sm", "md", "lg", "xl"]}>Responsive text</Box>

// Object syntax
<Box
  w={{ base: "100%", md: "50%", lg: "33%" }}
  p={{ base: 4, md: 8 }}
  display={{ base: "block", md: "flex" }}
>
  Responsive box
</Box>

Advanced Usage

Color Mode (Dark Mode)

import { useColorMode, useColorModeValue, IconButton } from "@chakra-ui/react"
import { MoonIcon, SunIcon } from "@chakra-ui/icons"

function ColorModeToggle() {
  const { colorMode, toggleColorMode } = useColorMode()
  const bg = useColorModeValue("white", "gray.800")
  const color = useColorModeValue("gray.800", "white")

  return (
    <Box bg={bg} color={color}>
      <IconButton
        aria-label="Toggle color mode"
        icon={colorMode === "light" ? <MoonIcon /> : <SunIcon />}
        onClick={toggleColorMode}
      />
    </Box>
  )
}
import { Modal, ModalOverlay, ModalContent, ModalHeader, ModalBody, ModalFooter, ModalCloseButton, useDisclosure } from "@chakra-ui/react"

function MyModal() {
  const { isOpen, onOpen, onClose } = useDisclosure()
  return (
    <>
      <Button onClick={onOpen}>Open Modal</Button>
      <Modal isOpen={isOpen} onClose={onClose} isCentered>
        <ModalOverlay />
        <ModalContent>
          <ModalHeader>Confirm Action</ModalHeader>
          <ModalCloseButton />
          <ModalBody>Are you sure you want to continue?</ModalBody>
          <ModalFooter>
            <Button variant="ghost" mr={3} onClick={onClose}>Cancel</Button>
            <Button colorScheme="blue">Confirm</Button>
          </ModalFooter>
        </ModalContent>
      </Modal>
    </>
  )
}

Troubleshooting

IssueSolution
Styles not applyingEnsure ChakraProvider wraps the entire app
Dark mode not workingAdd ColorModeScript before ChakraProvider; set initialColorMode in theme config
Flash of unstyled contentUse ColorModeScript in _document.tsx for Next.js
Bundle size largeImport components individually: import Button from '@chakra-ui/button'
Theme overrides ignoredEnsure extendTheme wraps your customizations; check component name casing
Responsive props not workingUse array or object syntax with correct breakpoint keys
Framer Motion errors (v2)Install compatible framer-motion version: npm install framer-motion@^10
TypeScript prop errorsExtend theme typings: use @chakra-ui/styled-system types
SSR hydration mismatchEnsure color mode matches between server and client