Setting Up Chakra UI: An Introductory Guide


Setting Up Chakra UI: A Comprehensive Introductory Guide

In the rapidly evolving landscape of frontend development, component libraries have become indispensable tools. They offer pre-built, reusable UI components that significantly accelerate development, ensure consistency, and often incorporate best practices like accessibility out of the box. Among the plethora of options available for React developers, Chakra UI has carved out a prominent niche, celebrated for its developer experience, flexibility, and adherence to modern UI principles.

This guide serves as a comprehensive introduction to setting up Chakra UI in your React projects. We’ll cover everything from the initial installation and basic configuration to exploring core concepts like theming, style props, responsive design, and color modes. Whether you’re starting a new project or considering integrating Chakra UI into an existing one, this guide aims to provide you with a solid foundation.

Table of Contents

  1. What is Chakra UI?
    • Core Philosophy
    • Key Features and Benefits
  2. Prerequisites
    • Node.js and npm/Yarn
    • A React Project (Create React App, Next.js, Vite, etc.)
  3. Installation
    • Using npm or Yarn
    • Peer Dependencies
  4. Setting Up the Provider
    • The Role of ChakraProvider
    • Wrapping Your Application
    • Integrating with Different Frameworks (CRA, Next.js, Vite)
  5. Basic Usage: Your First Chakra Component
    • Importing Components
    • A Simple Example
  6. Core Concepts Deep Dive
    • Style Props: The Heart of Chakra Styling
      • How They Work (Mapping to CSS)
      • Common Style Props (Layout, Spacing, Typography, Color, etc.)
      • Shorthand Props
      • Benefits: Colocation, Readability, Speed
    • Theming: Customizing the Look and Feel
      • The Default Theme Structure (Tokens)
      • Extending the Theme (extendTheme)
      • Customizing Colors, Fonts, Spacing
      • Component Styles and Variants
      • Using Theme Tokens in Style Props
    • Responsive Design: Building Adaptive Interfaces
      • Mobile-First Approach
      • Array Syntax for Breakpoints
      • Object Syntax for Breakpoints
      • Customizing Breakpoints
    • Color Modes: Effortless Dark/Light Mode
      • Configuration (initialColorMode, useSystemColorMode)
      • The useColorMode Hook
      • The useColorModeValue Hook
    • Component Composition: Building Complex UIs
      • Leveraging Primitive Components (Box, Stack, Flex)
      • Creating Custom Composite Components
    • Accessibility (A11y): Built-in Best Practices
      • ARIA Attributes and Roles
      • Focus Management
      • Keyboard Navigation
  7. Advanced Setup Considerations
    • CSS Reset: Ensuring Consistency
    • Custom Components with Chakra Styles
      • The chakra Factory Function
      • The useStyleConfig Hook
    • Server-Side Rendering (SSR) Integration
      • Considerations for Next.js
      • Potential Color Mode Flicker and Solutions
    • TypeScript Integration
      • Type Safety and Autocompletion
  8. Troubleshooting Common Setup Issues
    • ChakraProvider Not Found
    • Styles Not Applying Correctly
    • Theme Customizations Not Working
    • Color Mode Issues
  9. Conclusion and Next Steps
    • Recap of Benefits
    • Exploring Further Documentation
    • Community and Resources

1. What is Chakra UI?

Chakra UI is a popular, open-source React component library designed to make building accessible, modern web applications and websites faster and easier. Created by Segun Adebayo, it has gained significant traction within the React community for its thoughtful design, excellent developer experience, and focus on flexibility.

Core Philosophy

Chakra UI is built upon several core principles:

  1. Style Props: Instead of writing traditional CSS or using CSS-in-JS libraries with template literals, Chakra UI heavily utilizes style props. These are special props passed directly to components that map to CSS properties, allowing you to style elements directly within your JSX. This promotes style colocation and rapid prototyping.
  2. Composable Components: Components are designed to be small, focused, and easily composable. You can combine primitive components like Box, Stack, and Flex to build complex layouts and custom UI elements without needing excessive custom CSS.
  3. Accessibility (A11y) by Default: Chakra UI components follow WAI-ARIA standards where applicable. Features like proper focus management, keyboard navigation, and semantic HTML are built-in, reducing the burden on developers to implement these crucial aspects from scratch.
  4. Themeable and Customizable: While providing a solid default theme, Chakra UI makes extensive customization straightforward. You can easily override or extend colors, fonts, spacing, breakpoints, and even individual component styles to match your brand identity.
  5. Developer Experience: From clear documentation and TypeScript support to intuitive component APIs and helpful error messages, Chakra UI prioritizes making the development process smooth and enjoyable.
  6. Dark Mode Support: Built-in support for light and dark color modes is a first-class citizen, making it simple to implement this popular feature.

Key Features and Benefits

  • Ease of Styling: Style props drastically reduce the need to switch contexts between JSX and CSS files.
  • Rapid Development: Pre-built components for common UI patterns (buttons, modals, forms, menus, etc.) save significant time.
  • Guaranteed Accessibility: Reduces the risk of common accessibility pitfalls.
  • High Customizability: Adapts to diverse design requirements through its powerful theming system.
  • Responsive Design Made Easy: Intuitive syntax for applying styles based on screen size.
  • Built-in Dark Mode: Simple API for implementing and toggling color modes.
  • Strong TypeScript Support: Excellent type definitions for a safer and more productive development experience.
  • Active Community and Development: Regularly updated with new features, bug fixes, and strong community support.
  • Great Documentation: Comprehensive and easy-to-navigate documentation with plenty of examples.

2. Prerequisites

Before you can start setting up Chakra UI, ensure you have the following installed and ready:

Node.js and npm/Yarn

Chakra UI is typically used within a Node.js environment, primarily for managing packages and running build processes.

  • Node.js: You’ll need a recent version of Node.js. It’s generally recommended to use the Long Term Support (LTS) version. You can download it from the official Node.js website.
  • npm or Yarn: Node.js comes bundled with npm (Node Package Manager). Yarn is an alternative package manager that is also very popular. You can use either one. This guide will provide commands for both.
    • To check your Node.js version: node -v
    • To check your npm version: npm -v
    • To check your Yarn version (if installed): yarn -v

A React Project

Chakra UI is a React component library, so you need an existing React project or need to create a new one. Common ways to set up a React project include:

  • Create React App (CRA): A popular and officially supported way to create single-page React applications.
    bash
    npx create-react-app my-chakra-app
    # or
    yarn create react-app my-chakra-app
    cd my-chakra-app
  • Next.js: A powerful React framework for building server-rendered applications, static websites, and more.
    bash
    npx create-next-app@latest my-chakra-next-app
    # or
    yarn create next-app my-chakra-next-app
    cd my-chakra-next-app
  • Vite: A modern frontend build tool known for its extremely fast development server and optimized builds.
    bash
    npm create vite@latest my-chakra-vite-app --template react
    # or
    yarn create vite my-chakra-vite-app --template react
    cd my-chakra-vite-app
    npm install # or yarn install
  • Other Frameworks/Setups: Chakra UI can also be integrated into Gatsby, Remix, or custom webpack/babel configurations, but the setup might require slightly different steps, particularly around the Provider integration.

This guide will primarily focus on the setup within these common environments (CRA, Next.js, Vite). Ensure you have your chosen project structure set up and can run the development server (npm start, yarn dev, etc.) before proceeding.

3. Installation

Once your React project is ready, installing Chakra UI is straightforward using your preferred package manager.

Using npm or Yarn

Navigate to your project’s root directory in your terminal and run the installation command:

Using npm:

bash
npm install @chakra-ui/react @emotion/react @emotion/styled framer-motion

Using Yarn:

bash
yarn add @chakra-ui/react @emotion/react @emotion/styled framer-motion

Let’s break down these packages:

  • @chakra-ui/react: This is the core package containing all the Chakra UI components, hooks, and utilities.
  • @emotion/react & @emotion/styled: Chakra UI uses Emotion, a performant CSS-in-JS library, under the hood for styling. These are required peer dependencies. Emotion allows Chakra to handle dynamic styling, theming, and style props efficiently.
  • framer-motion: Chakra UI leverages Framer Motion for powering animations and transitions in components like Modal, Drawer, Accordion, etc. This makes complex animations easy to implement and customize.

Peer Dependencies

It’s crucial to install these peer dependencies (@emotion/react, @emotion/styled, framer-motion). If you forget them, your application will likely crash or fail to render Chakra components correctly, often with errors mentioning missing modules or context. Package managers (especially newer versions) might warn you about missing peer dependencies, but it’s best to install them explicitly alongside the main library.

4. Setting Up the Provider

For Chakra UI components to function correctly, access the theme, manage color modes, and apply global styles, your entire application (or the relevant part of it) needs to be wrapped with the ChakraProvider.

The Role of ChakraProvider

The ChakraProvider serves several key purposes:

  1. Theme Context: It uses React’s Context API to provide the theme object (containing colors, spacing, fonts, component styles, etc.) to all Chakra components within its subtree. This is how components know which styles to apply based on the theme configuration.
  2. Color Mode Management: It manages the application’s color mode (light or dark) and provides hooks (useColorMode, useColorModeValue) for components to react to mode changes.
  3. CSS Reset/Normalization: It typically applies a CSS reset (like Normalize.css or a custom reset) to ensure consistent styling across different browsers by removing default browser styles.
  4. Global Styles: Allows defining global CSS styles if needed.
  5. Directionality (LTR/RTL): Provides context for right-to-left language support if configured in the theme.

Essentially, ChakraProvider sets up the necessary environment for Chakra UI components to work seamlessly together.

Wrapping Your Application

You need to locate the root component of your application and wrap its returned JSX with <ChakraProvider>. Where this file is located depends on the framework you are using.

Integrating with Different Frameworks

Let’s see how to add the provider in the most common setups:

1. Create React App (CRA)

In a standard CRA project, the entry point is typically src/index.js or src/index.tsx. You should wrap your App component here.

“`jsx
// src/index.js (or src/index.tsx)
import React from ‘react’;
import ReactDOM from ‘react-dom/client’;
import { ChakraProvider } from ‘@chakra-ui/react’;
import App from ‘./App’;
// Optional: Import custom theme if you have one
// import theme from ‘./theme’;

const root = ReactDOM.createRoot(document.getElementById(‘root’));
root.render(

{/ Wrap the App component /}




);
“`

Note: If you create a custom theme (covered later), you’ll pass it as a prop to ChakraProvider: <ChakraProvider theme={myCustomTheme}>.

2. Next.js

In Next.js, the conventional place to wrap your application with providers is the pages/_app.js (or pages/_app.tsx) file. This file acts as a wrapper around all your page components.

“`jsx
// pages/_app.js (or pages/_app.tsx)
import { ChakraProvider } from ‘@chakra-ui/react’;
// Optional: Import custom theme
// import theme from ‘../theme’;

function MyApp({ Component, pageProps }) {
return (



);
}

export default MyApp;
“`

3. Vite

For Vite projects using React, the entry point is usually src/main.jsx or src/main.tsx. Similar to CRA, you wrap your App component here.

“`jsx
// src/main.jsx (or src/main.tsx)
import React from ‘react’;
import ReactDOM from ‘react-dom/client’;
import { ChakraProvider } from ‘@chakra-ui/react’;
import App from ‘./App’;
// Optional: Import custom theme
// import theme from ‘./theme’;
import ‘./index.css’; // Assuming you have a base CSS file

ReactDOM.createRoot(document.getElementById(‘root’)).render(





);
“`

Once you’ve added the ChakraProvider, Chakra UI is essentially set up and ready to use. Restart your development server if it was running to ensure the changes are picked up correctly.

5. Basic Usage: Your First Chakra Component

With the setup complete, let’s verify it by using a simple Chakra UI component.

Importing Components

Chakra UI components are typically imported directly from the @chakra-ui/react package.

jsx
import { Button, Box, Heading, Text } from '@chakra-ui/react';

A Simple Example

Let’s modify your main application component (e.g., src/App.js, pages/index.js, src/App.jsx) to include a few Chakra components.

“`jsx
// Example for App.js (CRA/Vite) or pages/index.js (Next.js)
import { Box, Heading, Text, Button, VStack } from ‘@chakra-ui/react’;

function HomePage() {
return (
// Box is a primitive div component with access to style props

{/ VStack arranges children vertically with spacing /}


Welcome to Chakra UI!


This is a basic example demonstrating Chakra UI component usage.



This is inside a styled Box.



);
}

// If in CRA/Vite, export default HomePage (or App)
// If in Next.js, export default HomePage
export default HomePage;
“`

If you run your development server now (npm start, yarn dev), you should see a page with:

  • A large heading styled in teal.
  • Some descriptive text.
  • A teal-colored button that triggers an alert on click.
  • A gray box containing some bold text.

Notice how we applied styles like padding (p={8}), font size (fontSize="lg"), color (color="teal.500"), background (bg="gray.100"), and spacing (spacing={4}) directly as props. This is the power of style props, which we’ll explore next. If this renders correctly, your Chakra UI setup is successful!

6. Core Concepts Deep Dive

Understanding the following core concepts is key to effectively using Chakra UI.

Style Props: The Heart of Chakra Styling

Style props are arguably the most defining feature of Chakra UI. They allow you to apply styles directly to components in your JSX, mapping familiar CSS properties to component props.

How They Work (Mapping to CSS)

Chakra UI uses Emotion internally to translate these props into actual CSS rules. For example:

  • <Box bg="tomato" w="100%" p={4} color="white">
    Translates roughly to:
    css
    .emotion-hash {
    background-color: tomato;
    width: 100%;
    padding: 1rem; /* Assuming theme.space[4] is 1rem */
    color: white;
    }

The values often map to tokens defined in the theme (e.g., p={4} maps to theme.space[4]), promoting consistency. You can also use raw CSS values (e.g., p="15px", color="#FF0000"), but using theme tokens is generally recommended.

Common Style Props

Chakra provides style props for a vast range of CSS properties, often with convenient shorthands:

  • Layout: width (or w), height (or h), display, boxSize (for equal width/height), overflow, position, zIndex, top, right, bottom, left.
  • Flexbox: display="flex", alignItems, justifyContent, flexDirection, flexWrap, flexGrow, flexShrink, flexBasis. (Helper components Flex and Stack simplify flexbox layouts).
  • Grid: display="grid", gridTemplateColumns, gridTemplateRows, gridColumn, gridRow, gridArea, gap, rowGap, columnGap. (Helper component Grid and GridItem).
  • Spacing: margin (or m), marginTop (or mt), marginRight (or mr), marginBottom (or mb), marginLeft (or ml), marginX (or mx), marginY (or my). Similarly for padding (p, pt, pr, pb, pl, px, py). Values usually map to theme.space.
  • Typography: color, fontFamily, fontSize, fontWeight, lineHeight, letterSpacing, textAlign, fontStyle, textDecoration, textTransform. Values often map to theme.colors, theme.fonts, theme.fontSizes, theme.fontWeights, etc.
  • Backgrounds: background (or bg), backgroundColor, backgroundImage, backgroundSize, backgroundPosition, backgroundRepeat.
  • Borders: border, borderWidth, borderStyle, borderColor, borderRadius.
  • Effects: boxShadow, opacity.
  • Interactivity: _hover, _focus, _active, _disabled, _selected, _checked, _invalid, _groupHover, _peerFocus etc. for pseudo-selectors and states.

Example using various props:

“`jsx
<Box
w=”300px”
h=”200px”
bg=”blue.100″
p={6}
m={4}
borderRadius=”lg” // maps to theme.radii.lg
boxShadow=”xl” // maps to theme.shadows.xl
textAlign=”center”
_hover={{ // Styles applied on hover
bg: ‘blue.200’,
boxShadow: ‘2xl’,
}}
_focus={{ // Styles for focus state
outline: ‘2px solid blue.500’,
}}
tabIndex={0} // Make it focusable

Styled Box
Using style props!

“`

Benefits of Style Props

  1. Colocation: Styles live right next to the component structure, making it easier to understand and modify the UI.
  2. Readability: For moderately styled components, JSX with style props can be very readable.
  3. Speed: Faster prototyping and iteration as you don’t need to constantly switch between files or define separate style classes/objects.
  4. Constraint-Based Design: Encourages using predefined theme tokens (spacing, colors), leading to more consistent UIs.
  5. Discoverability: Works well with TypeScript autocompletion, helping you discover available style props.

While powerful, overuse on deeply nested or complex components can sometimes lead to cluttered JSX. In such cases, component composition or defining custom component variants in the theme might be better approaches.

Theming: Customizing the Look and Feel

Chakra UI comes with a well-designed default theme, but most applications need customization to match specific branding or design systems. Chakra’s theming system is built on the concept of design tokens.

Design Tokens: These are named entities storing primitive UI values like colors, spacing units, font sizes, shadows, border radii, etc. Instead of hardcoding values (#FF0000, 16px), you use tokens (red.500, md).

The Default Theme Structure

You can inspect the default theme structure here. Key parts include:

  • breakpoints: Defines screen sizes for responsive design (sm, md, lg, xl, 2xl).
  • colors: A comprehensive color palette (e.g., gray.100, red.500, blue.700).
  • space: Spacing units used for margin, padding (1, 2, 3, …).
  • fontSizes: Font size scale (xs, sm, md, lg, xl, …).
  • fonts: Font families (body, heading, mono).
  • fontWeights: Font weights (normal, medium, bold).
  • lineHeights: Line heights (normal, none, short, tall).
  • letterSpacings: Letter spacing values.
  • radii: Border radius values (sm, md, lg, full).
  • shadows: Box shadow values (sm, md, lg, xl, outline).
  • zIndices: Z-index values (hide, auto, base, docked, dropdown, sticky, banner, overlay, modal, popover, skipLink, toast).
  • components: Default styles and variants for specific Chakra components (like Button, Input, Modal).

Extending the Theme (extendTheme)

To customize, you rarely replace the entire theme. Instead, you extend it using the extendTheme function.

  1. Create a theme file: Create a new file, e.g., src/theme.js or src/theme.ts.
  2. Import extendTheme:
    javascript
    // src/theme.js
    import { extendTheme } from '@chakra-ui/react';
  3. Define customizations: Create an object with the properties you want to override or add.
  4. Pass to extendTheme: Call extendTheme with your customization object.
  5. Export the theme: Export the result.
  6. Provide to ChakraProvider: Import this theme in your main application file (index.js, _app.js, main.jsx) and pass it to the ChakraProvider.

Example: Customizing Colors, Fonts, and Button Variant

“`javascript
// src/theme.js
import { extendTheme } from ‘@chakra-ui/react’;

// 1. Define custom colors, fonts, etc.
const colors = {
brand: { // Add a custom ‘brand’ color scheme
50: ‘#e6f7ff’,
100: ‘#b3e0ff’,
200: ‘#80c9ff’,
300: ‘#4db2ff’,
400: ‘#1a9cff’,
500: ‘#007acc’, // Your primary brand color
600: ‘#005fa3’,
700: ‘#00427a’,
800: ‘#002552’,
900: ‘#000829’,
},
secondary: { // Add a ‘secondary’ color
500: ‘#ff6b6b’,
}
};

const fonts = {
body: “‘Open Sans’, sans-serif”, // Use Open Sans for body
heading: “‘Montserrat’, sans-serif”, // Use Montserrat for headings
};

const components = {
Button: {
// Define base styles for all buttons
baseStyle: {
fontWeight: ‘bold’, // Make all buttons bold
borderRadius: ‘base’, // Use base border radius
},
// Define different variants
variants: {
// Override the default ‘solid’ variant
solid: (props) => ({
bg: props.colorScheme === ‘brand’ ? ‘brand.500’ : undefined, // Use brand color for brand scheme
color: props.colorScheme === ‘brand’ ? ‘white’ : undefined,
_hover: {
bg: props.colorScheme === ‘brand’ ? ‘brand.600’ : undefined,
},
}),
// Add a custom ‘outline-brand’ variant
‘outline-brand’: {
border: ‘2px solid’,
borderColor: ‘brand.500’,
color: ‘brand.500’,
_hover: {
bg: ‘brand.50’,
},
},
},
// Define default props
defaultProps: {
size: ‘md’,
variant: ‘solid’, // Default variant is solid
colorScheme: ‘gray’, // Default color scheme
},
},
// You can customize other components here (Input, Link, etc.)
Heading: {
baseStyle: {
fontFamily: ‘heading’, // Apply Montserrat automatically
color: ‘gray.700’,
},
},
Text: {
baseStyle: {
fontFamily: ‘body’, // Apply Open Sans automatically
},
},
};

// 2. Call extendTheme with your customizations
const customTheme = extendTheme({
colors,
fonts,
components,
// You can also customize spacing, breakpoints, etc.
// config: { // Example: customizing color mode behavior
// initialColorMode: ‘light’,
// useSystemColorMode: false,
// }
});

// 3. Export the theme
export default customTheme;
“`

Update ChakraProvider:

“`jsx
// e.g., src/index.js
import React from ‘react’;
import ReactDOM from ‘react-dom/client’;
import { ChakraProvider } from ‘@chakra-ui/react’;
import App from ‘./App’;
import customTheme from ‘./theme’; // Import your custom theme

const root = ReactDOM.createRoot(document.getElementById(‘root’));
root.render(

{/ Pass the theme here /}



);
“`

Now, any <Button colorScheme="brand"> will use your defined brand colors, and all headings will use Montserrat. You can also use the new variant: <Button variant="outline-brand">Custom Outline</Button>.

Using Theme Tokens in Style Props

You access theme tokens using dot notation strings:

  • color="brand.500" (uses theme.colors.brand[500])
  • p={4} (uses theme.space[4])
  • fontSize="xl" (uses theme.fontSizes.xl)
  • borderRadius="md" (uses theme.radii.md)
  • boxShadow="xl" (uses theme.shadows.xl)

This ensures consistency and makes it easy to update styles globally by just modifying the theme file.

Responsive Design: Building Adaptive Interfaces

Chakra UI makes responsive design intuitive and straightforward, adopting a mobile-first approach. Styles defined without a breakpoint apply to all screen sizes (base), and you override them for larger screens.

Default Breakpoints (can be customized in theme):

  • base: 0em
  • sm: 30em (~480px)
  • md: 48em (~768px)
  • lg: 62em (~992px)
  • xl: 80em (~1280px)
  • 2xl: 96em (~1536px)

Two main syntaxes:

1. Array Syntax:

Provide an array of values to a style prop. Each value corresponds to a breakpoint, starting from base.

“`jsx
<Box
w={[‘100%’, ‘80%’, ‘60%’, ‘40%’]} // Width: 100% base, 80% sm+, 60% md+, 40% lg+
p={[2, 4, 6]} // Padding: 2 base, 4 sm+, 6 md+
bg={[‘red.100’, ‘green.100’, ‘blue.100’]} // Bg: red base, green sm+, blue md+
textAlign={[‘center’, ‘left’]} // Text align: center base, left sm+

Responsive Box

“`

  • The first value (w[0], p[0], bg[0]) applies from base upwards.
  • The second value (w[1], p[1], bg[1]) applies from sm upwards, overriding the first.
  • The third value (w[2], p[2], bg[2]) applies from md upwards, overriding the second, and so on.
  • If the array has fewer values than breakpoints, the last value persists for larger breakpoints.
  • You can use null to skip a breakpoint and inherit the previous value: p={[2, null, 6]} (padding 2 for base/sm, padding 6 for md+).

2. Object Syntax:

Provide an object where keys are breakpoint names (base, sm, md, lg, xl, 2xl) and values are the styles for that breakpoint upwards. This is often considered more readable for complex responsive styles.

“`jsx
<Flex
// Starts as column, becomes row on medium screens
flexDirection={{ base: ‘column’, md: ‘row’ }}
p={{ base: 4, lg: 8 }} // Padding: 4 base to lg, 8 lg+
alignItems={{ base: ‘stretch’, md: ‘center’ }}

Item 1
Item 2

<Heading
size={{ base: ‘md’, md: ‘lg’, xl: ‘2xl’ }}

Responsive Heading

“`

The object syntax is particularly useful when you only need to target specific breakpoints without providing values for all intermediate ones.

Customizing Breakpoints:

You can define your own breakpoints in the theme:

“`javascript
// src/theme.js
import { extendTheme } from ‘@chakra-ui/react’;

const breakpoints = {
sm: ‘320px’,
md: ‘768px’,
lg: ‘960px’,
xl: ‘1200px’,
‘2xl’: ‘1536px’,
// You can remove or add breakpoints
‘custom’: ‘1024px’,
}

const theme = extendTheme({ breakpoints });

export default theme;
“`

Now, the array/object syntax will use these custom breakpoints.

Color Modes: Effortless Dark/Light Mode

Chakra UI provides excellent built-in support for toggling between light and dark themes.

Configuration:

You can configure the initial color mode and whether to respect the user’s system preference in the theme file:

“`javascript
// src/theme.js
import { extendTheme } from ‘@chakra-ui/react’;

const config = {
initialColorMode: ‘light’, // ‘light’, ‘dark’, or ‘system’
useSystemColorMode: false, // If true, initialColorMode is ignored and system preference is used
};

const theme = extendTheme({ config });

export default theme;
“`

  • initialColorMode: Sets the mode when the app first loads if useSystemColorMode is false.
  • useSystemColorMode: If true, Chakra UI will detect the OS preference (prefers-color-scheme) and use that initially. It also listens for OS theme changes.

The useColorMode Hook:

This hook provides the current colorMode (‘light’ or ‘dark’) and a toggleColorMode function.

“`jsx
import { useColorMode, Button, Box } from ‘@chakra-ui/react’;

function ColorModeSwitcher() {
const { colorMode, toggleColorMode } = useColorMode();

return (

Current mode: {colorMode}



);
}
“`

The useColorModeValue Hook:

Often, you need to apply different style values based on the current color mode. This hook simplifies that. It takes two arguments: the value to use in light mode and the value to use in dark mode.

“`jsx
import { useColorModeValue, Box, Text } from ‘@chakra-ui/react’;

function ThemedComponent() {
// Set background: gray.100 in light mode, gray.700 in dark mode
const bgColor = useColorModeValue(‘gray.100’, ‘gray.700’);
// Set text color: gray.800 in light mode, whiteAlpha.900 in dark mode
const textColor = useColorModeValue(‘gray.800’, ‘whiteAlpha.900’);

return (

This component adapts its colors to the mode!

);
}
“`

This is much cleaner than conditional logic inside your component based on colorMode. Chakra UI’s default theme already defines appropriate colors for components in both light and dark modes (e.g., gray.100 vs whiteAlpha.50), but useColorModeValue is essential for custom components or specific style overrides.

How it Works: Chakra UI achieves this by applying a class name (chakra-ui-light or chakra-ui-dark) or a data attribute (data-theme="light" or data-theme="dark") to the <body> or root element, and using CSS variables or Emotion’s theme context to switch values.

Component Composition: Building Complex UIs

Chakra UI encourages building interfaces by composing smaller, focused components rather than creating monolithic ones.

Primitive Components: Components like Box (a div element), Stack, HStack, VStack (for flexbox layouts), Flex (raw flexbox container), Grid, GridItem (for grid layouts), Text, Heading, Link, Icon are fundamental building blocks.

  • Box: The most basic layout component. Use it when you need a simple container with style props.
  • Stack, VStack, HStack: Arrange children linearly (vertically or horizontally) with automatic spacing between them using the spacing prop. Much easier than manual margins.
  • Flex: A Box with display: flex, useful for more complex flexbox alignments.
  • Grid, GridItem: For creating CSS Grid layouts easily using props like templateColumns, gap, etc.

Creating Custom Composite Components:

You can easily create your own reusable components by combining Chakra primitives and other Chakra components.

“`jsx
import { Box, Heading, Text, Icon, HStack } from ‘@chakra-ui/react’;
import { FaInfoCircle } from ‘react-icons/fa’; // Example using react-icons

// Create a reusable InfoCard component
function InfoCard({ title, children, …rest }) {
// Use useColorModeValue for adaptive styling
const bgColor = useColorModeValue(‘blue.50’, ‘blue.800’);
const iconColor = useColorModeValue(‘blue.500’, ‘blue.200’);

return (
// Pass any remaining props (…rest) to the outer Box



{title}


{children}


);
}

// Usage:
function MyPage() {
return (


Remember to save your work frequently.


Use component composition for cleaner code!


);
}
“`

This approach promotes reusability, maintainability, and keeps your component code clean and focused.

Accessibility (A11y): Built-in Best Practices

Accessibility is a core tenant of Chakra UI. The library aims to make it easier for developers to build applications usable by everyone, including people with disabilities who rely on assistive technologies (like screen readers).

Key A11y Features:

  • WAI-ARIA Standards: Components like Modal, Menu, Accordion, Tabs implement ARIA roles and attributes (e.g., aria-modal, role="menu", aria-selected) correctly out-of-the-box.
  • Focus Management: Modals trap focus, menus handle arrow key navigation, and focus indicators (_focus styles) are generally clear (though customizable).
  • Keyboard Navigation: Most interactive components are fully navigable and operable using only a keyboard.
  • Semantic HTML: Components generally render appropriate HTML elements (e.g., Button renders <button>).
  • Color Contrast: The default theme generally aims for accessible color contrast ratios, but always test your specific color combinations, especially custom ones.

While Chakra provides a strong foundation, developers still need to:

  • Use semantic elements appropriately (Heading for headings, Link for navigation).
  • Provide descriptive alt text for images (Image component).
  • Ensure proper label association for form elements (FormControl, FormLabel).
  • Test their applications with screen readers and keyboard navigation.

Chakra UI significantly lowers the barrier to creating accessible interfaces but doesn’t absolve the developer of responsibility entirely.

7. Advanced Setup Considerations

Beyond the basics, here are a few more aspects to consider for a robust setup.

CSS Reset: Ensuring Consistency

Chakra UI’s ChakraProvider automatically includes a CSS Reset based on modern practices (similar to Normalize.css plus some opinionated resets). This helps ensure your application looks more consistent across different browsers by neutralizing default browser styling inconsistencies.

In older versions of Chakra UI, you might have needed to explicitly import and use <CSSReset />. In current versions (v1+), this is generally handled internally by ChakraProvider. If you need no reset, you can pass resetCSS={false} to the provider, but this is rarely recommended unless you are providing your own comprehensive reset strategy.

Custom Components with Chakra Styles

Sometimes you need to create your own low-level components or integrate third-party components while leveraging Chakra’s styling system (style props, theme access, responsiveness).

1. The chakra Factory Function:

This function allows you to wrap standard HTML elements or other React components, making them compatible with Chakra’s style props.

“`jsx
import { chakra } from ‘@chakra-ui/react’;
import ThirdPartySlider from ‘some-slider-library’;

// Wrap a standard HTML element (e.g., )
const ChakraSpan = chakra(‘span’);

// Wrap a third-party component
const ChakraSlider = chakra(ThirdPartySlider);

function MyComponent() {
return (
<>

This is a chakra-fied span!

  <ChakraSlider
    mt={4} // Apply margin using style prop
    colorScheme="purple" // Assuming the slider accepts this, or you map it internally
    // ... other slider props
  />

);
}
``
The
chakra` factory is great for applying ad-hoc styles to elements or components that don’t natively support Chakra’s system.

2. The useStyleConfig Hook:

For creating more complex, themeable custom components (especially multi-part ones like Cards, Custom Inputs, etc.), useStyleConfig is the preferred approach. It allows your component to fetch styles defined within the components section of your theme.

Example: Creating a custom Card component:

a. Define styles in the theme:

“`javascript
// src/theme.js
import { extendTheme } from ‘@chakra-ui/react’;

const components = {
Card: { // Add a new ‘Card’ component key
// Define base styles for all parts
baseStyle: {
container: { // Styles for the main container part
borderWidth: ‘1px’,
borderRadius: ‘md’,
overflow: ‘hidden’,
boxShadow: ‘sm’,
},
header: { // Styles for an optional header part
paddingX: 4,
paddingY: 3,
borderBottomWidth: ‘1px’,
fontWeight: ‘bold’,
},
body: { // Styles for the main content part
padding: 4,
},
footer: { // Styles for an optional footer part
paddingX: 4,
paddingY: 3,
borderTopWidth: ‘1px’,
fontSize: ‘sm’,
color: ‘gray.500’,
},
},
// Define different variants (e.g., ‘elevated’, ‘outline’)
variants: {
elevated: {
container: {
boxShadow: ‘lg’,
},
},
outline: {
container: {
borderColor: ‘gray.300’,
boxShadow: ‘none’,
},
},
},
// Default props for the Card
defaultProps: {
variant: ‘outline’,
},
},
// … other component styles
};

const theme = extendTheme({ components });
export default theme;
“`

b. Create the Card component using useStyleConfig:

“`jsx
// src/components/Card.jsx
import { Box, useStyleConfig, chakra } from ‘@chakra-ui/react’;

// Use chakra factory for semantic elements if needed (optional)
const ChakraHeader = chakra(‘header’);
const ChakraFooter = chakra(‘footer’);

function Card(props) {
// Destructure props to get variant, size, colorScheme etc.
const { variant, children, …rest } = props;

// Fetch styles from the theme based on variant, size etc.
// ‘Card’ is the key we used in the theme’s components object
const styles = useStyleConfig(‘Card’, { variant });

// Apply the styles to the correct element/part using the __css prop
// The styles object will contain keys like ‘container’, ‘header’, ‘body’ etc.
return (

{/ Render children, allowing users to compose Card contents /}
{/ A more robust implementation might use Context or specific sub-components /}
{children}

);
}

// Optional: Create sub-components for structure (better practice)
function CardHeader(props) {
const styles = useStyleConfig(‘Card’, props);
return ;
}

function CardBody(props) {
const styles = useStyleConfig(‘Card’, props);
return ;
}

function CardFooter(props) {
const styles = useStyleConfig(‘Card’, props);
return ;
}

// Export the main component and sub-components
export { Card, CardHeader, CardBody, CardFooter };

// Usage Example:
import { Card, CardHeader, CardBody, CardFooter } from ‘./components/Card’;

function MyPage() {
return (
<>

Elevated Card

This card uses the ‘elevated’ variant defined in the theme.

Footer text

  <Card variant="outline" mt={4} maxW="sm">
     {/* Implicitly uses default 'outline' variant */}
    <CardHeader>Outline Card</CardHeader>
    <CardBody>
      <Text>This card uses the 'outline' variant.</Text>
    </CardBody>
  </Card>

);
}
``useStyleConfig` allows you to create truly themeable custom components that integrate seamlessly with Chakra’s system.

Server-Side Rendering (SSR) Integration

Chakra UI generally works well with SSR frameworks like Next.js out of the box, especially for basic styling. However, features like Color Mode that rely on browser APIs (like localStorage or prefers-color-scheme) might require specific setup to prevent issues like flickering on initial load.

Considerations for Next.js:

  • Provider Setup: Ensure ChakraProvider is correctly placed in _app.js or _app.tsx as shown earlier.
  • Color Mode Persistence: By default, Chakra UI uses localStorage to remember the user’s chosen color mode. This works fine on the client-side but isn’t available during SSR.
  • Potential Flicker: If using initialColorMode: 'dark' or useSystemColorMode: true, the server might initially render the page in the default mode (often light), and then the client-side JavaScript corrects it once it runs, causing a visible flash or flicker.

Solutions for Color Mode Flicker (Next.js):

Chakra UI provides mechanisms to mitigate this:

  1. Using Cookies: The recommended approach is often to store the color mode preference in a cookie instead of localStorage. Cookies are sent with the initial request, allowing the server to render the correct mode immediately.

    • You need to configure a colorModeManager that reads/writes to cookies. Chakra UI provides a cookieStorageManager helper.
    • Set this up in _app.js:
      “`jsx
      // pages/_app.js
      import { ChakraProvider, cookieStorageManagerSSR } from ‘@chakra-ui/react’;
      import theme from ‘../theme’; // Assuming theme has color mode config

      // Function to create a server-safe cookie manager
      export function getServerSideProps({ req }) {
      return {
      props: {
      // Pass the cookie string to the page component
      cookies: req.headers.cookie ?? ”,
      },
      }
      }

      function MyApp({ Component, pageProps, cookies }) { // Receive cookies prop
      // Create a manager instance based on the request cookies
      const colorModeManager = cookieStorageManagerSSR(pageProps.cookies);

      return (
      {/ Provide the manager /}


      );
      }

      export default MyApp;
      ``
      *Note: This
      getServerSidePropsin_app.jsopts your entire app into SSR. Consult Next.js docs for implications.* A simplercookieStorageManager` might suffice for apps without strict SSR needs on every page.

  2. Script in _document.js (Older/Alternative Method): Sometimes, a script was added to pages/_document.js to set the initial class or data attribute before React hydrates. This is generally less favored now compared to the cookie manager approach but might be seen in older examples.

Always refer to the latest Chakra UI documentation specific to Next.js integration for the most up-to-date recommendations.

TypeScript Integration

Chakra UI offers excellent first-party TypeScript support.

  • Type Safety: Most components, style props, and theme tokens are strongly typed, catching errors during development.
  • Autocompletion: Get intelligent suggestions for component props, style props, theme tokens (like colors, spacing values), and variants directly in your editor (like VS Code).

When creating custom themes or components with TypeScript:

  • Use extendTheme which is typed to merge your customizations correctly.
  • Define types for your custom theme structure if needed, although extendTheme often infers types well.
  • Type your custom component props appropriately.

“`typescript
// src/theme.ts
import { extendTheme, ThemeConfig } from ‘@chakra-ui/react’;

const config: ThemeConfig = { // Use ThemeConfig type
initialColorMode: ‘light’,
useSystemColorMode: false,
};

const theme = extendTheme({ config });

export default theme;

// src/components/MyButton.tsx
import { Button, ButtonProps } from ‘@chakra-ui/react’; // Import component and its props type

interface MyButtonProps extends ButtonProps { // Extend standard ButtonProps
customProp?: boolean;
}

function MyButton({ customProp, …rest }: MyButtonProps) {
// Use standard button props and your custom ones
return ;
}
“`

TypeScript significantly enhances the developer experience when working with Chakra UI’s extensive API surface.

8. Troubleshooting Common Setup Issues

If things aren’t working as expected after setup, check these common points:

  1. ChakraProvider Not Found / Styles Not Applying:

    • Cause: Most likely, you forgot to wrap your application root (or the relevant part) with <ChakraProvider>.
    • Solution: Double-check that ChakraProvider is correctly wrapping your App component in src/index.js (CRA), src/main.jsx (Vite), or Component in pages/_app.js (Next.js). Ensure it’s at a high enough level in the component tree.
  2. Component Errors (e.g., “Cannot read property ‘theme’ of undefined”):

    • Cause: Similar to the above, the component is being rendered outside the context provided by ChakraProvider. Or, less commonly, a peer dependency issue.
    • Solution: Verify the ChakraProvider wrap. Also, ensure @emotion/react, @emotion/styled, and framer-motion are correctly installed (check package.json and run npm install or yarn install again if needed). Delete node_modules and reinstall as a last resort.
  3. Theme Customizations Not Working:

    • Cause: The custom theme object might not be correctly created or passed to ChakraProvider.
    • Solution:
      • Ensure you’re using extendTheme correctly.
      • Verify that you are importing your customTheme file and passing the exported theme object to the theme prop of ChakraProvider: <ChakraProvider theme={customTheme}>.
      • Check for typos in your theme keys (e.g., colour instead of colors, component instead of components).
      • Make sure the structure within your theme customization matches the expected Chakra theme structure (e.g., colors: { brand: { 500: '#...' } }).
  4. Style Props Not Working:

    • Cause: The component might not be a Chakra component or a component wrapped with the chakra factory. Standard HTML elements (div, span) don’t accept style props directly.
    • Solution: Ensure you are using Chakra components (Box, Flex, Button, etc.) or components created using chakra('element'). Check for typos in prop names (pading instead of padding, bgColr instead of bgColor).
  5. Color Mode Issues (Flickering, Not Toggling):

    • Cause: Could be SSR-related flicker (see SSR section), incorrect theme configuration (config), or issues with the colorModeManager.
    • Solution:
      • For SSR flicker in Next.js, implement the cookieStorageManagerSSR approach.
      • Verify the config object (initialColorMode, useSystemColorMode) in your extendTheme call.
      • Ensure you’re using useColorMode and toggleColorMode correctly if building a custom toggle.
      • Check if useColorModeValue is used correctly for adaptive styles.
  6. TypeScript Errors:

    • Cause: Type mismatches, incorrect prop usage, or issues with theme typing.
    • Solution: Read the TypeScript error message carefully. Ensure props match the expected types (check component definitions or use editor autocompletion). Use type assertion (as) cautiously if necessary. Ensure your tsconfig.json is set up correctly for JSX/React.

Always consult your browser’s developer console for error messages, as they often provide valuable clues.

9. Conclusion and Next Steps

Chakra UI offers a compelling blend of developer experience, flexibility, and adherence to best practices, making it an excellent choice for building modern React applications. By leveraging its core concepts – Style Props, Theming, Responsive Syntax, Color Modes, Composition, and built-in Accessibility – developers can significantly accelerate their workflow and create high-quality, consistent, and accessible user interfaces.

We’ve covered the essential steps to get Chakra UI installed and configured in various common React environments, explored its fundamental features with practical examples, and touched upon more advanced considerations like custom components and SSR.

Recap of Benefits:

  • Speed: Rapid development through style props and pre-built components.
  • Consistency: Theme-based styling ensures UI uniformity.
  • Accessibility: Reduces the effort needed to build accessible applications.
  • Flexibility: Highly customizable via the theming system.
  • Developer Experience: Intuitive API, great documentation, TypeScript support.

Next Steps:

  1. Explore the Documentation: The official Chakra UI Documentation is excellent and comprehensive. Dive deeper into specific components, hooks, and advanced features not covered here.
  2. Experiment: The best way to learn is by doing. Build small projects or integrate Chakra UI into an existing one. Try customizing the theme extensively, building composite components, and implementing responsive layouts.
  3. Component Deep Dive: Explore the wide range of components Chakra offers for forms (Input, Select, Checkbox, FormControl), overlays (Modal, Drawer, Popover, Tooltip), navigation (Menu, Breadcrumb, Tabs), feedback (Alert, Spinner, Progress, Toast), and more.
  4. Join the Community: Engage with the Chakra UI community on platforms like Discord or GitHub Discussions for help, inspiration, and discussions.
  5. Contribute: If you find bugs or have ideas for improvements, consider contributing back to the open-source project.

Setting up Chakra UI is just the first step. Mastering its patterns and philosophy will empower you to build beautiful, functional, and accessible React applications more efficiently than ever before. Happy coding!


Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top