For enquiries call:

Phone

+1-469-442-0620

HomeBlogWeb DevelopmentChakra UI: Sleek UI Components for React

Chakra UI: Sleek UI Components for React

Published
24th Apr, 2024
Views
view count loader
Read it in
10 Mins
In this article
    Chakra UI: Sleek UI Components for React

    Chakra UI is a modern component library for React. It comes with a set of reusable and composable React components that you may use to create front-end apps. Its power comes from its simplicity, modularity, and accessibility. It can be used to create accessible React apps and to accelerate the development process. Emotion and Styled System are used in Chakra UI. Style systems are excellent architecture for constructing a UI component library. They make a lot of things a lot easier.

    What is Chakra UI in React? 

    Segun Adebayo designed and built Chakra UI, a sophisticated React component library for building front-end apps. The Chakra UI comes with concise, easy-to-understand documentation that shows us how to create a reusable component, allowing us to spend less time on the process and more time on other areas of the project.

    The Chakra-UI GitHub project now has 18.6k stars and 1.5k forks. In this tutorial, we'll look at how to use Chakra-UI Dark Mode in React.js when you click on a button. Chakra UI gives you a lot more styling and customization ability than other React UI libraries like React Bootstrap, Material UI, and so forth. If you like Tailwind CSS, you'll enjoy Chakra UI because it uses the same minimalistic and modular approach as Tailwind CSS. Check ReactJS learning path to start your learning and build concepts in ReactJS and land a good job.

    Why You Should Use Chakra UI?

    • Each one of Chakra UI's components are approachable using WAI-ARIA standards, which I believe is a hot topic for most of us.
    • Components are simple to edit, expand, and theme.
    • Components are small and easy to combine to construct larger structures.
    • Switching between other colour modes, such as light and dark, or perhaps any other collection of colours, will be a breeze.
    • Most libraries and frameworks are designed to help you achieve more with less in less time.
    • Although the community is relatively small, it is quite active.

    How to Get Started and Install Chakra UI 

    You can use npm or yarn to install Chakra UI and its dependencies. You must install Emotion, the CSS-in-JS library, as a peer dependency because Chakra UI requires it to handle component styles.

    npm install @chakra-ui/core @emotion/core @emotion/styled emotion-theming

    or

    yarn add @chakra-ui/core @emotion/core @emotion/styled emotion-theming

    You'll need the ThemeProvider, as well as a custom theme if you choose to go that route. ThemeProvider is the component that includes all of your components' suitable style.

    To personalise the UI, you can create your own custom theme. Custom colours, typography, and layout values are all possible. This step, however, is optional. Chakra UI comes with a customizable default theme.

    Emotion is used by Chakra UI to manage component styles. As you can see, peer requirements are not included with chakra-ui by default, thus you must install them manually.

    Wrap your React app under a ThemeProvider after that. Make the following changes to your index.js file.

    import React from "react";
    import ReactDOM from "react-dom";
    import App from "./App";
    import { ThemeProvider } from "@chakra-ui/core";
    ReactDOM.render(
      <ThemeProvider>
        <App />
      </ThemeProvider>,
      document.getElementById("root")
    );

    You can use Chakra UI components in your application once the fundamental setup is complete. Inputs, accordions, icons, tooltips, and other components are included in Chakra UI.

    The following code, for Chakra UI example, includes two typographic components, Text and Heading, as well as a Button enclosed in a Stack component.

    import { Button, Heading, Stack, Text } from "@chakra-ui/core"
    return (
      <Stack spacing={4} bg="white" p={8} borderRadius="lg">
        <Heading as="h1" size="md" color="primary.900">
          Learning Chakra UI
        </Heading>
        <Text as="p" fontSize="md" color="primary.500">
          Your first Chakra components:
        </Text>
        <Button variantColor="primary" isFullWidth>
          Click me
        </Button>
      </Stack>
    )

    As you can see in the example above, Stack is a layout utility component that makes it simple to stack items and apply a space between them. The Spacing prop is used to specify how far apart components should be. It accepts all acceptable Styled System props as well.

    Chakra UI Customization and Key Features  

    All Chakra components inherit values from the default theme by default. You may need to alter the theme tokens in some cases to meet your design requirements.

    1. Style Props

    Because Chakra UI is based on stylized systems, any component styles can be overridden or extended via props. As a result, stylesheets and inline styles are rarely required.

    In the Chakra UI component library, there are several shorthand variations of the style props. The official documentation has a detailed reference to style props.

    Here are a few of the most prevalent style props. CSS properties are spaced using these style prop shorthand.

    • m is used for margin.
    • mr is used for marginRight.
    • mt is used for marginTop.
    • p is used for padding.
    • pr is used for paddingRight.
    • pt is used for paddingTop.
    • py is used for padding-top and padding-bottom.

    2. Composition 

    Chakra UI dissolves components into smaller elements with limited properties to keep complexity low, then assembles them to ensure that styles and functionality are flexible and extensible.

    3. Accessibility 

    When developing components, accessibility is critical. The WAI-ARIA principles are followed by Chakra UI components, which provide keyboard navigation, focus management, accurate aria-* attributes, and focus trapping and restoration for modal dialogues. Each authored component's accessibility report can be found in a file called accessibility.md.

    4. Thematic

    Style systems have their own set of theme requirements. You can change the look of your app or download new themes by following these precise theme parameters.

    You must first generate a theme.js file, which you must then supply as a JSON object. Custom values can be set in the theme object to determine the application's colour palette, font stacks, type scale, breakpoints, and so on.

    import { theme } from "@chakra-ui/core";
    // Adding custom colors
    const customTheme = {
      ...theme,
      colors: {
        ...theme.colors,
        brand: {
          900: "#1d4044",
          800: "#234e52",
          700: "#285e61",
        },
      },
    };

    5. Dark Mode

    Implementing dark mode with Chakra UI is really straightforward because it comes with it out of the box. The majority of the components in this package work in dark mode.

    The useColorMode hook in Chakra UI allows you to alter the colour mode of the application.

    To enable colour mode in your app, you must utilise ColorModeProvider and wrap your app with a ColorModeProvider.

    import React from "react";
    import { ThemeProvider, ColorModeProvider } from "@chakra-ui/core";
    import customTheme from "./theme";
    function TurnOnColorMode({ children }) {
      return (
        <ThemeProvider theme={customTheme}>
          <ColorModeProvider>{children}</ColorModeProvider>
        </ThemeProvider>
      );
    }

    6. Responsive Design

    Chakra UI supports mobile-first responsive designs. On mobile devices, it maintains its performance. As a result, you won't have to add media queries and nested styles to your code by hand.

    Every style prop in the theme definition is supported by the responsive design. At certain breakpoints, you can also modify the style of properties.

    Exploring the Chakra UI React Component 

    Chakra UI comes with a tonne of high-quality React components. These are a couple of them:

    Input Components

    Text inputs, number inputs, choose inputs, checkboxes, radio buttons, and switch inputs are all available in Chakra UI.

    Layout Components

    You can quickly apply responsive layouts to numerous components using Chakra UI. It's made up of layout components like Box and Stack that make it simple to customise your components with properties. As a result, you may use CSS props to pass in attributes like background and justifyContent.

    To organise a set of components with identical spacing, use the stack command. Although it is vertical by default, you may use isInline to change that.

    • For receiving style props, you can utilise Box as a div element.
    • Everything may be wrapped in a CSS Grid container using Grid.
    • Everything can be wrapped in a Flexbox container using Flex.

    As a result, you may utilise all of the flex attributes on the wrapper as props, such as flexDirection, alignItems, justifyContent, and so on.

    BreadCrumb 

    You can even use the Breadcrumb component to make things easier to navigate between pages. It improves how consumers navigate back to previous page levels on a website, which is especially useful if the website has a lot of pages or products. Breadcrumb, BreadcrumbItem, BreadcrumbLink, and BreadcrumbSeparator are four breadcrumb-related components in Chakra UI.

    Drawer 

    Chakra UI's Drawer is a one-of-a-kind component. It's a mechanism that'd work well in any side navbar. For controlling the state of the drawer, the Drawer component leverages Chakra UI's unique useDisclosure hook, which includes isOpen, onOpen, and onClose.

    Limitations of Chakra UI 

    Chakra UI is a React component library that makes use of the Emotion and Styled System. Components that employ utility properties for styling < Button color="primary" textAlign="center"> are possible thanks to the combination of both Styled system and emotion. It's like Tailwind crossed with React properties, but it's related to your JS theme's CSS (note the use of primary for color). It's similar to other Styled System-based UI frameworks like Rebass, but with more features.

    Impossible to Style Some Components 

    Switch, Checkbox, and a few others can be styled superficially (by adding additional CSS on top), but they have core elements that you can't style.

    The Switch

    The <div> inside the <Switch>, is styled and you don't have access to it with the style props provided. I wanted to do things like scale up the inner elements, but their styles were out of reach, and the variables they employed effected other areas of the system. Chakra comes in three sizes (small, medium, and large), however I just used the "large" (scaling it as needed with transform: scale(2)).

    The Check Box

    I also needed to modify the icon used for the Checkbox>, but I couldn't do so without duplicating the Chakra source code and swapping it in. This is because the Checkbox icon is nested inside an <Icon> component that returns an SVG icon. You could use CSS to delete that icon and replace it with another using the background property, but that's a bit hacky (since the icon still shows in DOM).

    The Tooltip

    And this one was unique.  The arrow in the< Tooltip> required to be styled. Because it's a React "portal" (meaning it's not a direct child of the Tooltip component near the DOM's root), you'll need to copy the source.

    import React from 'react'
    import { Tooltip as ChakraTooltip } from '@chakra-ui/core'
    export const Tooltip = ({ children, ...props }) => (
      <ChakraTooltip
        borderWidth="3px"
        borderStyle="solid"
        borderColor="black"
        {...props}
      >
        {children}
      </ChakraTooltip>
    )
    export default Tooltip

    You might use a selector to retrieve the required object if it were a nested child, but it'd be difficult in this instance (since it's out of the component scope that doesn't have a specified class name or ID to aim). In a fundamental sense, you can style it by altering the background or text colour.

    As of now, Chakra suggests using their <PseudoBox> to create your own components, yet I feel like I'm starting from scratch and causing myself additional problems in the future by failing to account for every unusual scenario. To avoid having to roll my own, I use component libraries.

    Check out  web development certificate online by knowledgehut and get training in various fields of web development.

    Defaults are Difficult to Apply Since Varied Colours Have Limitations

    I needed to construct a default button with a border and the design system's "main" colour. Chakra comes with a couple different button styles or "variants" by default. A borderless button and a bordered button with a transparent backdrop are two options.

    I made a new component (<Button>) that took a ChakraButton and gave it some basic border and background colour properties. I also passed the remaining props (...props), such as the background colour, so they could be overridden.

    import React from 'react'
    import { Button as ChakraButton } from '@chakra-ui/core'
    export const Button = ({ children, ...props }) => (
      <ChakraButton
        variantColor="primary"
        color="black"
        borderWidth="3px"
        borderStyle="solid"
        borderColor="black"
        fontWeight="bold"
        px={3}
        py={2}
        display="block"
        height="auto"
        _hover={{
          backgroundColor: 'primary.300',
          color: 'black',
        }}
        _pressed={{
          backgroundColor: 'primary.700',
          color: 'white',
        }}
        {...props}
      >
        {children}
      </ChakraButton>
    )
    export default Button

    However, I had to override the text colour to ensure contrast (it defaults to white, which isn't accessible with the "primary" colour). This means that if I give the component another variantColor (which is a BG and text colour), it will use the hard-coded "black" as its text colour. This isn't true for all variantColors, as some may require white text (requiring you to override the colour prop too). As a result, you'll have to create a manual variant for each hue (similar to developing your own variant prop that acts as a large switch() statement to change utility properties).

    It also complicates the process because you have to alter several style settings to account for all of the component states.

    No Variants 

    I'm not sure why Chakra adopted so much from Styled System, and even using variants, yet doesn't let users change variants through the theme. For each variant, you'll need to make a new component and use utility properties to apply the different styles.

    It performs, but it compresses your app or UI library with basic wrappers that do styling. To develop variants, you end up performing your own custom wiring and repeating the process with more components.  

    Styled System and other libraries were intended to provide more efficient alternatives to constructing your own variant API.

    No Way to Theme Some Components 

    The <Alert> component in Chakra is essentially a "status message" element that you put above forms or other areas to inform the user of a mistake, success, or other event. You can give it several React state props to use (like error). I was able to essentially style the base component (only needed to add a border), but I couldn't locate any instructions or methods for decorating it based on the status prop.

    I tried utilizing theme variants for components and putting them under the object identified for each state, but it didn't work:

    const theme = {
      ...ChakraBaseTheme,
      variants: {
        Alert: {
          error: {
            bg: 'red',
            color: 'white',
          },
        },
      },
    }

    I couldn't find any settings for the status or variants in general after looking through the theme file and type interfacing.

    The styles are then derived using a hook and a preset file containing object-based styles for bright and dark modes, after examining the source code for <Alert>. This should ideally default to somewhere in the theme so that it may be overridden.

    For next steps, check out our blog posts about top ReactJS features which makes IT best for development.

    Looking to enhance your coding skills? Dive into the world of Python with our unique and engaging Python certification course. Unleash your potential and become a Python pro today!

    A Full Circle

    Overall, Chakra UI is distinguished by its very configurable design approach. It has the option to swap between different themes. It also includes Flexbox and style utilities for creating your own design systems.

    Chakra UI is a user interface that has recently received a lot of traction. It is continually improving as a potential new library, and the buzz around it is growing. More components are likely to be introduced in the near future. As a result, you should think about employing it in your next React project. For complete guide for ReactJS learning path KnowledgeHut brings you best course to get the complete knowledge at one place.

    Frequently Asked Questions (FAQs)

    1Which is better Chakra UI or Material UI?

    If your project is small or medium in size and you need something fast, the Chakra UI is the way to go. Because it is simple to learn and carry. Material UI has a proven track record of stability, and if you want to build larger applications, you can use it because of its scalability and active community.

    2Is Chakra UI open-source?

    Yes, ChakraUI is an open-source.

    3Is Chakra UI customizable?

    It is customizable and reusable.

    4How do I add Chakra UI to React?

    To install chakra-ui, run the following command in your project's root directory.

    npm install @chakra-ui/core @emotion/core @emotion/styled emotion-theming

    5How do I upgrade my chakra UI?
    • Install the framer-motion package if it isn't already installed. Within components, we use this to manage animations and transitions.
    • Remove the emotion-theming package. Emotion-theming has been removed from emotion v11, and all of its functionality has been relocated to @emotion/react.
    • @emotion/core should be renamed to @emotion/react. Following the release of v11 by the emotionjs team, @emotion/core was renamed to @emotion/react.
    • @chakra-ui/core should be renamed to @chakra-ui/react.
    • Update to version 11 of the @emotion/styled package.
    Profile

    Sachin Bhatnagar

    Blog Author

    Sachin Bhatnagar is an experienced education professional with 20+ years of expertise in Media & Entertainment and Web Technologies. Currently, as the Program Director - Full-Stack at KnowledgeHut, he excels in curriculum development, hands-on training, and strategic deployment of industry-centric educational programs. His online training programs on have attracted over 25,000 learners since 2014. He actively contributes to the development of full-stack training products, leveraging KnowledgeHut's advanced learning platform. Collaborating with organizational leaders, he ensures the success of these programs and has created several technology programs prominently featured in KnowledgeHut's course offerings.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon