The Top 5 Chakra UI Tips and Tricks for React Developers
Chakra UI is a popular component library for building customizable React applications. It provides a solid foundation of reusable UI components that allow you to rapidly create polished, professional-looking interfaces. Here at Ayrshare, we recently rewrote our social media dashboard in Chakra UI – we were previously using an offshoot of Bootstrap. No matter how much research you do or POCs, you never know until you start the real work. Thankfully, we found Chakra UI lived up to its reputation: the breadth of components, speed, and flexibility was fantastic.
Let’s now dive into what we discovered during our dashboard rebuild: our top five Chakra UI tips and tricks for React developers.
1. Theme Customization Made Easy
One of the greatest strengths of Chakra UI is its theme customization capabilities. With just a few lines of code, you can tailor the colors, typography, component styles, and other visual aspects of your entire application.
To customize your theme, start by creating a custom theme object. You can either extend the default Chakra UI theme using the extendTheme function or build your theme from scratch. Here’s an example of extending the default theme with some custom colors, fonts, and component overrides:
import { extendTheme } from "@chakra-ui/react";
import "@fontsource-variable/inter";
const customTheme = extendTheme({
colors: {
brand: {
100: "#f0e8e2",
// ...
900: "#3f2c1d",
},
},
fonts: {
heading: "'Inter Variable', sans-serif",
body: "'Inter Variable', sans-serif",
},
components: {
Button: {
baseStyle: {
fontWeight: "semibold",
borderRadius: "lg",
},
sizes: {
xl: {
h: "56px",
fontSize: "lg",
px: "32px",
},
},
variants: {
outline: {
border: "2px solid",
borderColor: "brand.500",
color: "brand.500",
},
},
},
},
});
Let’s break down what’s happening here:
– We import the extendTheme
function from Chakra UI and the Inter font from @fontsource-variable/inter
.
– We create a customTheme
object using extendTheme
, which allows us to extend the default Chakra UI theme.
– We define custom colors under the colors
key, in this case, a brand
color palette with shades from 100 to 900.
– We set the fonts
for headings and body text to use the Inter font.
– We customize the Button
component by specifying base styles, sizes, and variants. The base style sets the font weight and border radius for all buttons, the sizes object defines a custom xl
size, and the variants object creates a new outline
variant.
To apply your custom theme across your application, wrap your root component with the ChakraProvider
and pass in your theme object:
import { ChakraProvider } from "@chakra-ui/react";
function App() {
return (
<ChakraProvider theme={customTheme}>
{/* Your application code */}
</ChakraProvider>
);
}
2. Responsive Styles Made Simple
Chakra UI makes it a breeze to create responsive designs that adapt to different screen sizes. It provides a convenient array syntax that allows you to specify styles for different breakpoints.
const breakpoints = {
sm: "30em",
md: "48em",
lg: "62em",
xl: "80em",
"2xl": "96em",
};
To apply responsive styles, simply pass an array of values to a style prop, where each value corresponds to a breakpoint:
<Stack direction={["column", "row"]} spacing="24px">
<Box w={["100%", "50%", "25%"]} h="200px" bg="blue.500" />
<Box w={["100%", "50%", "75%"]} h="200px" bg="red.500" />
</Stack>
Here’s how this works:
– The Stack
component will display its children in a column
on small screens (the base breakpoint), and in a row
on screens wider than the sm
breakpoint (30em).
– The width of the first child Box
will be 100% on small screens, 50% on medium screens (30em to 48em), and 25% on screens wider than 48em.
– The width of the second child Box
will be 100% on small screens, 50% on medium screens, and 75% on screens wider than 48em.
You can also use the object syntax for more explicit control:
<Grid
templateColumns={{
base: "1fr",
sm: "repeat(2, 1fr)",
md: "repeat(3, 1fr)",
lg: "repeat(4, 1fr)",
}}
gap={6}
>
<GridItem bg="blue.500" h="200px" />
<GridItem bg="red.500" h="200px" />
<GridItem bg="green.500" h="200px" />
<GridItem bg="purple.500" h="200px" />
</Grid>
This Grid
component uses the object syntax to define its templateColumns
responsively:
– On the base breakpoint, it will display its children in a single column.
– On the sm
breakpoint, it will display its children in 2 columns.
– On the md
breakpoint, it will display its children in 3 columns.
– On the lg
breakpoint and above, it will display its children in 4 columns.
3. Useful Default Style Props
Chakra UI provides a set of default style props that act as shorthand for commonly used CSS properties. These props can save you a significant amount of time and keep your code concise and readable. Here are some examples:
<Box
m={4}
p={3}
bg="blue.500"
color="white"
fontSize="xl"
fontWeight="bold"
borderRadius="md"
boxShadow="base"
_hover={{
bg: "blue.600",
color: "white",
boxShadow: "lg",
}}
>
Hover over me!
</Box>
Let’s dissect the style props used in this `Box` component:
– m={4}
sets the margin on all sides to 1rem (Chakra UI uses a 4px base).
– p={3}
sets the padding on all sides to 0.75rem.
– bg="blue.500"
sets the background color to the `blue.500
` color from the theme.
– color="white"
sets the text color to white.
– fontSize="xl"
sets the font size to 1.25rem.
– fontWeight="bold"
sets the font weight to bold.
– borderRadius="md"
sets the border radius to 0.375rem.
– boxShadow="base
` applies a base box shadow.
– _hover
is a pseudo style prop that applies styles on hover. In this case, it changes the background color to blue.600
, text color to white, and applies a large box shadow.
4. Conditional Rendering Based on Screen Size
Chakra UI provides a handy useMediaQuery hook that allows you to conditionally render components based on the current screen size. This is particularly useful for creating responsive layouts that adapt to different devices. Here’s an example:
import { useMediaQuery } from "@chakra-ui/react";
function NavBar() {
const [isLargerThan768] = useMediaQuery("(min-width: 768px)");
return (
<Box bg="blue.500" color="white" py={4}>
<Container maxW="container.lg">
<Flex align="center" justify="space-between">
<Text fontSize="2xl" fontWeight="bold">
My Logo
</Text>
{isLargerThan768 ? (
<HStack spacing={8}>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/contact">Contact</Link>
</HStack>
) : (
<IconButton
icon={<HamburgerIcon />}
aria-label="Open menu"
onClick={onOpen}
/>
)}
</Flex>
</Container>
</Box>
);
}
In this example:
– We use the useMediaQuery
hook to check if the screen width is larger than 768px. The result is stored in the isLargerThan768
variable.
– In the JSX, we conditionally render either a row of navigation links (HStack
) or a hamburger menu icon (IconButton
) based on the value of isLargerThan768
.
– If isLargerThan768
is true (screen width is larger than 768px), we render the HStack
with the navigation links.
– If isLargerThan768
is false (screen width is smaller than 768px), we render the IconButton
with the hamburger menu icon.
– The onClick
prop on the `IconButton
could be used to trigger the opening of a drawer or menu on small screens.
5. Accessible and Customizable Drawer Component
Chakra UI’s Drawer component is a versatile tool for creating sidebars, modal dialogs, and other overlay elements. One particularly useful feature is the ability to create a responsive drawer that adapts its behavior based on the screen size.
For example, you might want a sidebar that is always open on larger screens but can be toggled on smaller screens using a hamburger menu icon. Here’s how you can achieve this with Chakra UI:
First, we customize the Drawer component by adding a variant called permanent
. This variant will make sure the sidebar will be always open:
import { useMediaQuery } from "@chakra-ui/react";
function Sidebar({ isOpen, onClose }) {
const [isLargerThan1024] = useMediaQuery("(min-width: 1024px)");
return (
<Drawer
isOpen={isOpen}
placement="left"
onClose={onClose}
variant={isLargerThan1024 ? "permanent" : ""}
>
<DrawerOverlay>
<DrawerContent>
<DrawerCloseButton />
<DrawerHeader>Sidebar</DrawerHeader>
<DrawerBody>{/* Sidebar content */}</DrawerBody>
</DrawerContent>
</DrawerOverlay>
</Drawer>
);
}
Then, you can use this new variant in your Drawer component:
import { useMediaQuery } from "@chakra-ui/react";
function Sidebar({ isOpen, onClose }) {
const [isLargerThan1024] = useMediaQuery("(min-width: 1024px)");
return (
<Drawer
isOpen={isOpen}
placement="left"
onClose={onClose}
variant={isLargerThan1024 ? "permanent" : ""}
>
<DrawerOverlay>
<DrawerContent>
<DrawerCloseButton />
<DrawerHeader>Sidebar</DrawerHeader>
<DrawerBody>{/* Sidebar content */}</DrawerBody>
</DrawerContent>
</DrawerOverlay>
</Drawer>
);
}
Let’s break this down:
– We use the useMediaQuery
hook to check if the screen width is larger than 1024px and store the result in the isLargerThan1024
variable.
– The Drawer
component receives the isOpen
and onClose
props to control its visibility and provide a way to close it.
– We conditionally set the variant prop of the Drawer
based on the screen size:
– If isLargerThan1024
is true (screen width is larger than 1024px), we set the variant
to "permanent"
, which means the drawer will be always visible.
– If isLargerThan1024
is false (screen width is smaller than 1024px), we set the variant
to ""
, which means the drawer will be a temporary overlay that can be opened and closed, the default behavior.– The DrawerOverlay
, DrawerContent
, DrawerCloseButton
, DrawerHeader
, and DrawerBody
components are used to structure the drawer and provide accessibility features like a close button and proper ARIA roles.
Keep Exploring
Chakra UI is a flexible library that can boost your productivity when building React applications. By leveraging its theme customization, responsive styles, default style props, conditional rendering, and accessible components, you can create good-looking interfaces with minimal effort.
Remember, the key to mastering any tool is to explore its capabilities, experiment with different approaches, and find what works best for your specific use case. The examples and explanations in this article should give you a solid foundation to build upon.
About Ayrshare
Ayrshare is a social media API that allows you to publish posts, get analytics, manage comments, and sends direct messages on the social networks directly from your platform. Learn more in our social media API docs.