DEV Community

Cover image for Creating simple React components with Chakra UI
Mina
Mina

Posted on • Updated on

Creating simple React components with Chakra UI

Chakra UI is growing in popularity with each passing month. The component library created by Segun Adebayo has amassed over 460k weekly downloads and 8 million downloads in April. It also has over 70k Github stars and 3500+ forks – an impressive feat for a package that was released in November 2018. It’s almost like the offspring of a Tailwind and Bootstrap marriage as it embodies all the great things we loved about both libraries and still offers an array of customisable features at a very granular level yet still looks great straight out-of-box. Let’s see how easy it is to use, shall we?


Installing Chakra UI

To use Chakra UI in your React project, you have to do an npm or yarn install – but unlike Tailwind, you don’t have to install Autoprefixer and PostCSS.

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

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

After the installation is complete, confirm that you have it installed by checking your package.json file.

  "dependencies": {
    "@chakra-ui/icons": "^2.0.18",
    "@chakra-ui/react": "^2.5.5",
    "@emotion/react": "^11.10.6",
    "@emotion/styled": "^11.10.6",
    "framer-motion": "^10.11.2",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-query": "^3.39.3"
  }
Enter fullscreen mode Exit fullscreen mode

Once you’ve confirmed that all packages are installed you have to wrap the ChakraProvider component around your app.

import * as React from 'react'

// 1. import `ChakraProvider` component
import { ChakraProvider } from '@chakra-ui/react'

function App() {
  // 2. Wrap ChakraProvider at the root of your app
  return (
    <ChakraProvider>
      <TheRestOfYourApplication />
    </ChakraProvider>
  )
}
Enter fullscreen mode Exit fullscreen mode

This way, all the sections, components and pages of your app can use Chakra UI. Once this is done we’re good to go.

Creating a card component

For this article, we’re going to create a card component that displays a profile image, title, description and a CTA button all within the card.

I’ve designed the card already on Figma, this is what the final component should look like:

Profile card from figma

Now here’s where Chakra UI shines.

<Box
        p="30px"
        border="1px"
        display="flex"
        flexDirection="column"
        width="300px"
        borderRadius="10px"
        borderColor="gray.300"
      >
        <Image
          src="https://avatars.githubusercontent.com/u/6916170?v=4"
          h="80px"
          w="80px"
          borderRadius="50px"
          bg="yellow"
          mb="20px"
        />
        <Text as="h2" fontSize="20px" fontWeight="bold" mb="6px">
          Here's a title
        </Text>
        <Text as="p" mb="30px">
          Here's a description it should be much longer so I'm making it much
          longer because it is what it is
        </Text>
        <Button colorScheme="blue">See more</Button>
      </Box>
Enter fullscreen mode Exit fullscreen mode

Let’s break it down. The first container is like a div tag – very similar features and properties of a div tag, Image translates to an <img> tag. If you look closely at the Text props, there’s an “as” beside it. This tells Chakra to render them as semantic tags, and thus the “as=’h2’” and “as=’p’”. When they’re both rendered, they come out as h2 and p tags – it does all the heavy lifting for you.

What tags look like

Let’s explore the “as” keyword a bit more

The “as” keyword is a nifty yet powerful tool as it allows you to build a semantic and SEO-compliant webpage in just one line. For this example, we’re going to create an image tag but with a Box tag.

<Box
        p="30px"
        border="1px"
        display="flex"
        alignItems="center"
        width="360px"
        borderRadius="10px"
        borderColor="gray.300"
      >
        <Box
          as="img"
          src="https://avatars.githubusercontent.com/u/6916170?v=4"
          h="80px"
          w="80px"
          borderRadius="50px"
          bg="yellow"
          mr="20px"
        />
        <Box>
          <Box as="h2" fontWeight="bold" fontSize={20}>
            Name of this guy
          </Box>
          <Box as="p">Phone: 099687983</Box>
          <Box as="p">Email: paroro@gmail.com</Box>
        </Box>
      </Box>
Enter fullscreen mode Exit fullscreen mode

I’ve taken the liberty to write everything using the “Box” tag, but now take a look at how they are rendered in the browser.

The power of the as keyword in transforming chakra ui tags to semantic tags

All the semantic tags I’ve defined using the “as” keyword are rendered as (pun not intended) their HTML counterparts but just because you could, doesn’t mean you should. Just like using div tags in all your code isn’t advised, using Box tags can be confusing if done excessively. Here’s what the component looks like.

Sematic tags using as keyword

Now let’s consume some public API

I’ll be using React Query to consume a public API – this way we get to see how to wrap our component in a map function. I’ll be using Random User Generator’s API; you can get it right here: https://randomuser.me/. As the name goes, you’re going to get random user details every single time you call the API. Once you install React Query and set it up, we’re ready to go. I’ve picked react query because it’s fairly easy to use even for beginners. Here’s the code to make a call to the API:

const { data } = useQuery(["profile"], async () => {
    const req = await axios.get("https://randomuser.me/api/");
    return req.data;
  });
Enter fullscreen mode Exit fullscreen mode

I’ve decided to pass only the data query state as it will help us keep the focus around creating components with Chakra UI. Once this is done, we can use the query state inside our component.

{data.results.map((result, i) => (
        <Box
          key={i}
          p="30px"
          border="1px"
          display="flex"
          alignItems="center"
          justifyContent="center"
          minW="300px"
          maxW="500px"
          borderRadius="10px"
          borderColor="gray.300"
        >
          <Box
            as="img"
            src={result.picture.thumbnail}
            h="80px"
            w="80px"
            borderRadius="50px"
            bg="yellow"
            mr="20px"
          />
          <Box>
            <Box as="h2" fontWeight="bold" fontSize={20}>
              {result.name.first + " " + result.name.last}
            </Box>
            <Box as="p">Phone: {result.phone}</Box>
            <Box as="p">Email: {result.email}</Box>
          </Box>
        </Box>
      ))}
Enter fullscreen mode Exit fullscreen mode

It slots in nicely into our component and as I said earlier, we can generate a different profile each time we make an API call.

API call

API call result

Chakra UI is a popular and highly customizable React component library that provides developers with the tools they need to create beautiful and responsive user interfaces. With its easy-to-use syntax, comprehensive documentation, and active community support, it's no wonder that Chakra UI has gained popularity among developers in recent years.

By following the steps outlined in this tutorial, you should be able to create a simple yet functional component using Chakra UI in no time. Whether you're a seasoned developer or just starting, Chakra UI is worth considering for your next project.


More reading:

https://chakra-ui.com Image credit: chakra

Top comments (0)