Exploring the Chakra UI React Component Library

Joshua Hall

Despite my love for Tailwind CSS over other frameworks, I have always been disappointed by the lack of components like what we get with more fully fledged-out frameworks like Bootstrap and Materialize. I recently discovered the perfect solution to this problem: Chakra UI.

Chakra UI follows the same minimalistic and modular approach as Tailwind CSS, so you don’t need to waste anymore time undoing and overriding the default configurations.

In this article, we’re going to get started exploring the best of what this framework can do for us and why it’s unique.

Installation

Installation is a bit awkward since there are a few peer dependencies which, I think, should just come with it by default, but that’s how it is for some reason ¯\_(ツ)_/¯.

We just need Chakra UI itself and a few things from Emotion, since Chakra UI is dependent on 👩‍🎤 emotion, the CSS-in-JS library.

We’ll make use of npx and Create React App to initialize our React app:

$ npx create-react-app chakra-app
$ npm install @chakra-ui/core @emotion/core @emotion/styled emotion-theming

Setup

Before we can do anything we need to wrap our whole app in a ThemeProvider, which establishes all of the default styles for our components.

index.js

import { ThemeProvider } from "@chakra-ui/core";

const ThemedApp = () => <ThemeProvider> <App /> </ThemeProvider>;

ReactDOM.render(<ThemedApp />, document.getElementById('root'));

Layout

Besides our normal UI components like sliders and dropdowns, Chakra UI gives us a few “meta components” (not the official term), for easily adding a responsive layout of multiple components. With all of them you can pass-in the properties you’d expect, like bg or justifyContent in CSS as props.

  • Stack - Groups a set on components with equal spacing, is vertical by default but can be overridden with isInline.
  • Flex - Wraps everything in a Flexbox container.
  • Grid - Wraps everything in a CSS Grid container.
  • Box - Just a div for receiving style props.

App.js

import { Stack, Flex, Box, Grid } from "@chakra-ui/core";

const App = () => {
  const flexSettings = {
    flex: "1",
    minW: "300px",
    textAlign: "center",
    color: "white",
    mx: "6",
    mb: "6"
  };

  const gridSettings = {
    w: "100%",
    textAlign: "center",
    color: "white",
  };

  return (
    <div>
      <Flex w="100%" justify="space-between" flexWrap="wrap">
        <Box {...flexSettings} bg={"red.500"}>I'm a box</Box>
        <Box {...flexSettings} bg={"blue.500"}>I'm a box</Box>
        <Box {...flexSettings} bg={"green.500"}>I'm a box</Box>
        <Box {...flexSettings} bg={"purple.500"}>I'm a box</Box>
      </Flex>

      <Grid w="100%" templateColumns="repeat(auto-fit, minmax(300px, 1fr))" gap={6}>
        <Box {...gridSettings} bg={"red.500"}>I'm a box</Box>
        <Box {...gridSettings} bg={"blue.500"}>I'm a box</Box>
        <Box {...gridSettings} bg={"green.500"}>I'm a box</Box>
        <Box {...gridSettings} bg={"purple.500"}>I'm a box</Box>
      </Grid>
    </div>
  );
};

Styling

Since Chakra UI is based on Emotion for styling, is allows for using CSS-in-JS and adds its own shorthand for common properties in the same style as Tailwind CSS, that’s why we were able to use w and templateColumns instead of width and gridTemplateColumns.

If you’re unfamiliar with this approach to styling, it’s a way of writing your CSS so you get all the JavaScript goodies that even Sass doesn’t come with, like connecting a style to the state of a component.

In this example, we’re basing the styles of a box off the component’s state and using a little UI to manipulate it.

App.js

const BoxController = () => {
  let [boxHeight, editHeight] = useState(20);
  let [boxColor, editColor] = useState('red');
  let [colorIntensity, editIntensity] = useState(500);

  const boxSettings = {
    flex: "1",
    textAlign: "center",
    color: "white",
    h: `${boxHeight}px`,
    bg: `${boxColor}.${colorIntensity}`
  };

  return (
    <div>
      <Box {...boxSettings}>I'm a Box</Box>
      <Flex justifyContent="space-around">
        <Stack>
          <Heading size="md">Size</Heading>
          <Button variantColor="red" onClick={() => editHeight(boxHeight -= 10)} border="none">Shrink</Button>
          <Button variantColor="green" onClick={() => editHeight(boxHeight += 10)} border="none">Grow</Button>
        </Stack>

        <Stack>
          <Heading size="md">Color</Heading>

          <Flex w="200px" justifyContent="space-between">

            <Stack>
              <Button variantColor="green" onClick={() => editColor('green')} border="none">Green</Button>
              <Button variantColor="blue" onClick={() => editColor('blue')} border="none">Blue</Button>
              <Button variantColor="red" onClick={() => editColor('red')} border="none">Red</Button>
            </Stack>

            <Stack>
              <Button variantColor="gray" variant="outline" onClick={() => editIntensity(colorIntensity -= 100)} border="none">Lighter</Button>
              <Button variantColor="gray" variant="outline" onClick={() => editIntensity(colorIntensity += 100)} border="none">Darker</Button>
            </Stack>

          </Flex>
        </Stack>
      </Flex>
    </div>
  );
};

Components

We obviously can’t go over every component, so let’s just focus on a few that are unique to Chakra UI.

Drawer

The drawer component is a clean little slide out mechanism that would be perfect for any side navbar. Note that it uses Chakra’s custom useDisclosure hook that gives us isOpen, onOpen, and onClose for controlling the state of our drawer and any similar components, like a modal.

App.js

import {
  Drawer,
  DrawerBody,
  DrawerFooter,
  DrawerHeader,
  DrawerOverlay,
  DrawerContent,
  DrawerCloseButton,
  Input,
  Button,
  useDisclosure,
  Stack,
  Textarea
} from "@chakra-ui/core"

const SignUpForm = () =>  {
  const { isOpen, onOpen, onClose } = useDisclosure();
  const btnRef = useRef();

  return (
    <div>
      <Button ref={btnRef} variantColor="teal" border="none" onClick={onOpen}>
        Sign Up
      </Button>
      <Drawer
        isOpen={isOpen} placement="bottom"
        onClose={onClose} finalFocusRef={btnRef}
      >
        <DrawerOverlay />
        <DrawerContent>

          <DrawerCloseButton border="none" />
          <DrawerHeader>Sign up Now</DrawerHeader>
          
          {/* Form */}
          <DrawerBody >
            <Stack height="30vh">
              <Input w="98%" placeholder="Name" />
              <Input w="98%" placeholder="Email" />
              <Textarea w="98%" h="100%" placeholder="Message" />
            </Stack>
          </DrawerBody>

          <DrawerFooter>
            <Button variantColor="red" border="none" mr={3} onClick={onClose}>
              Cancel
            </Button>
            <Button variantColor="blue" border="none">Save</Button>
          </DrawerFooter>

        </DrawerContent>
      </Drawer>
    </div>
  );
}

Loaders

Chakra UI offers us a nice array of animated loaders that are insanely easy to customize. In this example I’ve added a loop to see our loaders in action, but they don’t need to be based on anything external, they can also be completely static.

App.js

import {
  Stack,
  CircularProgress,
  CircularProgressLabel,
  Progress,
  Spinner
} from "@chakra-ui/core"

const Spinners = () => {
  let [progress, update] = useState(0)

  const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)

  useEffect(() => setInterval(() => {
    // Reset to 0 when reaches 100
    update(progress < 100 ? progress += randomNum(0, 4) : 0)
  }, 500), [])

  return (
    <div>
      <Stack>
        <CircularProgress color="green" isIndeterminate>
          <CircularProgressLabel>{progress}%</CircularProgressLabel>
        </CircularProgress>
        <CircularProgress value={progress} size="100px" thickness={0.1} color="purple" />
        <Progress value={progress} w="90%" />
        <Progress value={progress + 10} w="90%" hasStripe isAnimated />
        <Spinner
          thickness="3px"
          speed="1s"
          emptyColor="gray.200"
          color="blue.500"
          size="2xl"
        />
      </Stack>
    </div>
  );
}

Themes

Something I have yet to see from any other framework is the ability to set themes over the entirety of your app. Whether it be a dark theme or a winter theme we can easily customize the style across our whole site/app in one place.

In this example I’ve added a few boxes whose designs and text will be based on the holiday season. I personally love when sites give you the option to pick which design you like best, like Alligator.io does. 😉

index.js

import { useTheme, ThemeProvider } from "@chakra-ui/core"


const ThemedApp = () => {
  const theme = useTheme()
  const customTheme = {
    ...theme,
    colors: { ...theme.colors },
    holidays: {
        text: {
          none: "Welcome to the site!",
          stPatricksDay: "Happy St.Patty's Day!",
          valentinesDay: "Happy Valentines Day!",
          halloween: "Good luck trick-or-treating!",
          christmas: "Merry Christmas!"
        },
        colors: {
            none: {
              "one": "#808080",
              "two": "#808080",
              "three": "#808080"
            },
            stPatricksDay: {
              "one": "#224D17",
              "two": "#60A830",
              "three": "#099441"
            },
            valentinesDay: {
              "one": "#b11d4d",
              "two": "#fd6fa0",
              "three": "#e986a3"
            },
            halloween: {
              "one": "#810806",
              "two": "#BF200E",
              "three": "#FA4113"
            },
            christmas: {
              "one": "#44b09e",
              "two": "#e0d2c7",
              "three": "#e01c34"
            },
        }
      }
  };
  return (
    <div>
      <ThemeProvider theme={customTheme}><App /></ThemeProvider>
    </div>
  )
}

App.js

import {
  Flex,
  Button,
  useTheme,
  Box
} from "@chakra-ui/core"

const HolidayPicker = () => {
  const [holiday, updateHoliday] = useState("none")
  const theme = useTheme()

  const holidayText = theme.holidays.text[holiday]
  const holidayColor = theme.holidays.colors[holiday]

  const btnStyles = {
    border: 'none',
    h: '25px',
    borderRadius: '20px',
    color: 'white',
    fontWeight: 'bold',
    cursor: 'pointer'
  }
  return (
    <div>
      <Flex justifyContent="space-around">
        <Box bg={holidayColor.one} w="100%" h="400px" color="white">{holidayText}</Box>
        <Box bg={holidayColor.two} w="100%" h="400px" color="white">{holidayText}</Box>
        <Box bg={holidayColor.three} w="100%" h="400px" color="white">{holidayText}</Box>
      </Flex>

      <Flex justifyContent="space-around" mt="20px">
        <Button bg={theme.holidays.colors.none} {...btnStyles}
          onClick={() => updateHoliday('none')}>None</Button>
        <Button bg={theme.holidays.colors.stPatricksDay} {...btnStyles}
          onClick={() => updateHoliday('stPatricksDay')}
        >St.Patrick's Day</Button>
        <Button bg={theme.holidays.colors.valentinesDay} {...btnStyles}
          onClick={() => updateHoliday('valentinesDay')}
        >Valentine's Day</Button>
        <Button bg={theme.holidays.colors.halloween} {...btnStyles}
          onClick={() => updateHoliday('halloween')}
        >Halloween</Button>
        <Button bg={theme.holidays.colors.christmas} {...btnStyles}
          onClick={() => updateHoliday('christmas')}
        >Christmas</Button>
      </Flex>
    </div>
  );
}

Closing Thoughts

Together with TailwindCSS, Chakra UI has easily become one of the essential tools in all of my projects. It’s constantly improving and even now there are a few pull requests like appBar and carousel components that’ll probably be added soon. I hope this was enough to help you decide if Chakra UI deserves to be in your React/UI arsenal.

  Tweet It

🕵 Search Results

🔎 Searching...

Sponsored by #native_company# — Learn More
#native_title# #native_desc#
#native_cta#