Chakra UI

Ayush KumarAyush Kumar
5 min read

Chakra UI Documentation

1. Installation

npm i @chakra-ui/react @emotion/react @emotion/styled framer-motion

1.2 📄 package.json - dependencies

{
  "name": "chakra-ui",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@chakra-ui/icons": "^2.1.1",
    "@chakra-ui/react": "^2.8.1",
    "@emotion/react": "^11.11.1",
    "@emotion/styled": "^11.11.0",
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "framer-motion": "^10.16.4",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.17.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },

2.Set Up Chakra Provider at the root of application

in your index.jsx, index.tsx or App.jsx

import React from 'react';

// 1. import `ChakraProvider` component
import { ChakraProvider } from '@chakra-ui/react'    // ⭐⭐⭐⭐⭐⭐🎯
import theme from './theme.js';
import './index.css'

function App() {
  // 2. Wrap ChakraProvider at the root of your app
  return (
    <ChakraProvider>    // ⭐⭐⭐⭐⭐⭐🎯
      <TheRestOfYourApplication />
    </ChakraProvider>
  )
}

3. Extend Theme

import { extendTheme, theme as base, withDefaultColorScheme, withDefaultSize, withDefaultVariant } from "@chakra-ui/react";
import {mode} from '@chakra-ui/theme-tools'

const replaceExisting = {
    variants: {
        filled: {
            field: {
                _focus: {
                    borderColor: "myBrand.500",
                }
            }
        }
    }
}

const theme = extendTheme(
    {
        fonts: {
            // heading: `Montserrat Alternates, ${base.fonts.heading}`,
            heading: `Recursive, ${base.fonts.heading}`,
            body: "Inter",
        },

        colors: {
            myBrand: {
                50: "#f5fee5",
                100: "#e1fbb2",
                200: "#cdf781",
                300: "#b8ee56",
                400: "#a2e032",
                500: "#8ac919",
                600: "#71ab09",
                700: "#578602",
                800: "#3c5e00",
                900: "#203300",
            }
        },

        components: {
            Input: { ...replaceExisting },
            Select: { ...replaceExisting },
            Textarea: {
                variants: {
                    filled: {
                        _focus: { borderColor: "myBrand.500" }
                    }
                }
            },
            Checkbox: {
                // Define the styles for the Checkbox component
                baseStyle: {
                    control: {
                        _focus:{
                            // Change the ring color for the checkbox
                            ring: "2", // You can use any Chakra UI color token or a CSS color value
                            ringColor: "myBrand.500"
                        }
                    },
                },
            },

            Button: {
                variants: {
                    myPrimary: (props) => ({                        
                        bg: "myBrand.500",  // Background color
                        color: "white",   // Text color

                        bg: mode("myBrand.500", 'white')(props),  // Background color
                        color: mode("white", "black")(props),   // Text color

                        _focus: {                          
                            ring: 2,
                            ringColor: "myBrand.500",
                        },
                        _hover: {
                            bg: "myBrand.600",  // Hover background color
                        },
                    })
                }
            }
        }
    },

    withDefaultColorScheme({
        colorScheme: 'myBrand',
    }),
    withDefaultVariant({
        variant: "filled",
        components: ["Input", "Select", "Textarea"]
    })
);

export default theme;

Import Google Font in css

📁src/📄index.css

@import url('https://fonts.googleapis.com/css2?family=Inter&family=Montserrat&family=Montserrat+Alternates:ital@1&family=Recursive&display=swap');

4.Create Navbar

import React, { useState } from 'react';
import { Avatar, Button, Center, Drawer, DrawerBody, DrawerCloseButton, DrawerContent, DrawerFooter, DrawerHeader, DrawerOverlay, Flex, Input, List, ListItem, Menu, MenuButton, MenuDivider, MenuGroup, MenuItem, MenuList, Popover, PopoverArrow, PopoverBody, PopoverCloseButton, PopoverContent, PopoverHeader, PopoverTrigger, Stack, Switch, useColorMode, useDisclosure } from '@chakra-ui/react'

import { IconButton} from '@chakra-ui/react';
import { HamburgerIcon } from '@chakra-ui/icons';


const Navbar = () => {
    const { isOpen, onOpen, onClose } = useDisclosure()
    const myBtnRef = React.useRef()

    const avatarOptions = ['Profile', 'Setting', 'Privacy', 'Logout']
    const { toggleColorMode } = useColorMode()
    return (
        <React.Fragment>

            <Drawer
                isOpen={isOpen}
                placement='right'
                onClose={onClose}
                finalFocusRef={myBtnRef}
            >
                <DrawerOverlay />
                <DrawerContent>
                    <DrawerCloseButton />
                    <DrawerHeader>Create your account</DrawerHeader>

                    <DrawerBody>
                        <Input placeholder='Type here...' />
                    </DrawerBody>

                    <DrawerFooter>
                        <Button variant='outline' mr={3} onClick={onClose}>
                            Cancel
                        </Button>
                        <Button colorScheme='blue'>Save</Button>
                    </DrawerFooter>
                </DrawerContent>
            </Drawer>

            <Flex h={14} bg={'myBrand.500'} alignItems={'center'} justifyContent={"space-between"} px={6} >
                <IconButton
                    ref={myBtnRef}
                    onClick={onOpen}    // ⭐
                    icon={<HamburgerIcon />}
                    //   icon={<CloseIcon />}
                    aria-label="Open/Close Menu"
                    //   onClick={toggleMenu}
                    variant="solid"
                    fontSize="3xl"
                />
                {/* ------------------------------------- */}
                <Popover>
                    <PopoverTrigger>
                        <Avatar cursor={'pointer'} />
                    </PopoverTrigger>
                    <PopoverContent>
                        <PopoverArrow />
                        <PopoverCloseButton />
                        <PopoverHeader>Confirmation!</PopoverHeader>
                        <PopoverBody>
                            <List spacing={1} >
                                {avatarOptions.map((item, index) => (
                                    <Button colorScheme='gray' key={index} cursor={'pointer'} w={'full'} rounded={'none'} >{item}</Button>
                                ))}
                            </List>
                        </PopoverBody>
                    </PopoverContent>
                </Popover>                
                {/* ------------------------------ */}

                <Stack direction='row'>                    
                    <Button onClick={toggleColorMode} colorScheme='yellow' size='md' ></Button>
                    {/* <Button onClick={toggleColorMode} variant={"solid"} mx={3} colorScheme={"purple"} >Try Changing the theme.</Button> */}

                </Stack>

                {/* ------------------------------ */}
                <Menu>
                    <MenuButton colorScheme='pink'>
                        <Avatar cursor={'pointer'} />
                    </MenuButton>
                    <MenuList>
                        <MenuGroup title='Profile'>
                            <MenuItem>My Account</MenuItem>
                            <MenuItem>Payments </MenuItem>
                        </MenuGroup>
                        <MenuDivider />
                        <MenuGroup title='Help'>
                            <MenuItem>Docs</MenuItem>
                            <MenuItem>FAQ</MenuItem>
                        </MenuGroup>
                    </MenuList>
                </Menu>

            </Flex>
        </React.Fragment>
    )
}

export default Navbar

5.Create Input Form

import { Button, Checkbox, FormControl, FormLabel, GridItem, Heading, Input, Select, SimpleGrid, Text, Textarea, VStack } from "@chakra-ui/react";
import React from 'react';

const YourDetails = () => {
    return (
        <React.Fragment>
            <VStack h={"full"} w={'full'} p={10} spacing={10} align={'flex-start'}  >
                <VStack spacing={2} align={'flex-start'} >
                    <Heading>Your Details</Heading>
                    <Text>If you already have an account, please click here to login.</Text>
                </VStack>

                {/* LHS Main Body */}
                <SimpleGrid column={2} columnGap={3} rowGap={2}  >
                    <GridItem colSpan={1} >
                        <FormControl>
                            <FormLabel>First Name</FormLabel>
                            <Input placeholder="Enter your Name" />
                        </FormControl>
                    </GridItem>
                    <GridItem colSpan={1} >
                        <FormControl>
                            <FormLabel>Last Name</FormLabel>
                            <Input placeholder="Enter last Name" />
                        </FormControl>
                    </GridItem>
                    <GridItem colSpan={2} >
                        <FormControl>
                            <FormLabel>Address</FormLabel>
                            <Textarea placeholder="Enter your Address ..."  />
                        </FormControl>
                    </GridItem>
                    <GridItem colSpan={1} >
                        <FormControl>
                            <FormLabel>City</FormLabel>
                            <Input placeholder="City Name" type="text" />
                        </FormControl>
                    </GridItem>

                    <GridItem colSpan={1} >
                        <FormControl>
                            <FormLabel>Country</FormLabel>
                            <Select placeholder="Select Country" >
                                <option value="USA">United States of America</option>
                                <option value="India">India</option>
                            </Select>
                        </FormControl>
                    </GridItem>

                    <GridItem colSpan={2} py={3} >
                        <Checkbox colorScheme={'myBrand'} >Ship to the Billing Address</Checkbox>
                    </GridItem>

                    <GridItem colSpan={2} >
                        {/* <Button colorScheme="teal" size="lg" w={"full"} mt={4}>Submit</Button> */}
                        <Button variant={"myPrimary"} colorScheme="myBrand" size="lg" w={"full"} mt={4}>Submit</Button>
                    </GridItem>
                </SimpleGrid>

            </VStack>

        </React.Fragment>
    )
}

export default YourDetails

6.Add to Cart Section

import { AspectRatio, Button, Divider, HStack, Heading, Image, Stack, Text, VStack, useColorMode, useColorModeValue } from "@chakra-ui/react";
import React from 'react';

const Cart = () => {
    const { toggleColorMode } = useColorMode();
    const bg_Color = useColorModeValue('teal.50', 'teal.900')
    const textColor = useColorModeValue('gray.600',)

    return (
        <React.Fragment>
            <VStack h={"full"} w={'full'} p={10} spacing={10} align={'flex-start'} bg={bg_Color} >
                <VStack align={'flex-start'}  >
                    <Heading>Your Cart</Heading>
                    <Text>
                        If the price is too hard, on your eyes,
                        <Button onClick={toggleColorMode} variant={"solid"} mx={3} colorScheme={"purple"} >Try Changing the theme.</Button>
                    </Text>
                </VStack>

                <HStack justifyContent={'space-between'} w={'full'} >
                    <HStack spacing={6} >
                        <AspectRatio width={16} ratio={1} >
                            <Image src="/img/skateboard.jpeg" ></Image>
                        </AspectRatio>

                        <Stack direction={'row'} spacing={1} w={'fit-content'} justify={'space-between'} alignItems={'center'}  >
                            <VStack align={'flex-start'}  >
                                <Heading size={'md'} >Skate Board</Heading>
                                <Text>SKT1073</Text>
                            </VStack>
                        </Stack>
                    </HStack>

                    <Heading textAlign={'end'} fontSize={{ base: 24, md: 36 }} fontWeight={"bold"}   >$ 199</Heading>
                </HStack>

                <VStack spacing={4} alignItems={'stretch'} w={'full'} >

                    <HStack justifyContent={'space-between'} >
                        <Text color={textColor} fontWeight={'bold'} >Subtotal: </Text>
                        <Heading size={"sm"} >$ 119</Heading>
                    </HStack>

                    <HStack justifyContent={'space-between'} >
                        <Text color={textColor} fontWeight={'bold'} >Shipping: </Text>
                        <Heading size={"sm"} >$ 19</Heading>
                    </HStack>

                    <HStack justifyContent={'space-between'} >
                        <Text color={textColor} fontWeight={'bold'} >Taxes (estimated): </Text>
                        <Heading size={"sm"} >$ 23</Heading>
                    </HStack>
                </VStack>

                <VStack w={"full"}  >
                    <Divider w={"full"} borderWidth={'1px'} borderColor={useColorModeValue('black', 'white')} />
                    <HStack w={'full'} justifyContent={'space-between'} mt={2} >
                        <Text color={textColor} fontWeight={'bold'} >Total:</Text>
                        <Heading size={'sm'} >$ 162</Heading>
                    </HStack>
                </VStack>

            </VStack>
        </React.Fragment>
    )
}

export default Cart
0
Subscribe to my newsletter

Read articles from Ayush Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ayush Kumar
Ayush Kumar

A passionate MERN Stack Developer from India I am a full stack web developer with experience in building responsive websites and applications using JavaScript frameworks like ReactJS, NodeJs, Express etc.,