Social Media Marketing

Top Chakra UI Tips and Tricks for Responsive Developers

[ad_1]

Chakra UI is a popular library for building custom React apps. It provides a solid foundation of reusable UI components that allow you to quickly create polished, professional-looking interfaces. Here at Ayrshare, we recently rewrote our social media dashboard in Chakra UI – previously we were using Bootstrap Sprout. No matter how much research or POCs you do, you won’t know until you start the actual work. Thankfully, we found Chakra UI to live up to its reputation: the range of components, speed, and flexibility were great.

Now let’s dive into what we discovered while rebuilding our dashboard: our top five Chakra UI tips and tricks for React developers.

1. Theme customization Made Easy

One of the biggest strengths of Chakra UI is its ability to customize the theme. With just a few lines of code, you can combine colors, typography, component styles, and other visual features of your entire app.

To customize your theme, start by creating a custom theme object. You can extend the default Chakra UI theme using the extendedTheme function or build your own theme from scratch. Here’s an example of extending the default theme with some custom colors, fonts, and component overlays:

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 analyze what is happening here:

– We import i extendTheme function from Chakra UI and Inter font from @fontsource-variable/inter.

– We build a customTheme something you use extendThemewhich allows us to extend the default Chakra UI theme.

– We define custom colors under colors the key, in this case, is a brand Color palette with shades from 100 to 900.

– Set i fonts for headings and body text to use the Inter font.

– We customize the Button section by specifying basic styles, sizes, and variations. The basic style sets the font weight and border radius for all buttons, the size element defines the custom xl size, and a different thing creates a new one outline different.

To apply your custom theme to your entire application, bind your root component with ChakraProvider and pass in your theme object:

import { ChakraProvider } from "@chakra-ui/react";

function App() {
  return (
    
      {/* Your application code */}
    
  );
}

2. Responsive Styles Made Easy

Chakra UI makes it a breeze to create responsive designs that adapt to different screen sizes. It provides a simple array syntax that allows you to specify styles for different array points.

const breakpoints = {
  sm: "30em",
  md: "48em",
  lg: "62em",
  xl: "80em",
  "2xl": "96em",
};

To use responsive styles, simply pass the same values ​​to the style property, where each value corresponds to a breakpoint:


  
  

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:


  
  
  
  

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:


  Hover over me!

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 (
    
      
        
          
            
            
            
            My Logo
          
          {isLargerThan768 ? (
            
              Home
              About
              Contact person
            
          ): (
            } aria-label="Open menu" onClick={Open} /> )}
        
      
    
  
  
  
  ); }

In this example:

– We use the useMediaQuery hook to check if the screen width is greater than 768px. The result is stored in isLargerThan768 flexible.

– In JSX, we conditionally provide any line of navigation links (HStack) or the hamburger menu icon (IconButton) based on the value of isLargerThan768.

– If isLargerThan768 is true (screen width is greater than 768px), we provide i HStack with navigation links.

– If isLargerThan768 false (screen width is less than 768px), we provide i IconButton with the hamburger menu icon.

– The onClick prop to `IconButton can be used to trigger the opening of a drawer or menu on small screens.

5. Accessible and Customized Wardrobe Part

The Chakra UI Cabinet component is a versatile tool for creating sidebars, modal dialogs, and other overlay features. One very useful feature is the ability to create a responsive drawer that adapts its behavior based on screen size.

For example, you might want a sidebar that stays open on large screens but can be toggled on small screens using the hamburger menu icon. Here’s how you can do this with Chakra UI:

First, we customize the Cabinet component by adding a variable called permanent. This exception will ensure that the sidebar will always be open:

import { useMediaQuery } from "@chakra-ui/react";
function Sidebar({ isOpen, onClose }) {
const [isLargerThan1024] = useMediaQuery("(min-width: 1024px)");

return (
isOpen={isOpen}
placement="left"
onClose={onClose}
variant={isLargerThan1024 ? "permanent" : ""}
>



Sidebar
{/* Sidebar content */}



);
}

Then, you can use this new variant in your Cabinet component:

import { useMediaQuery } from "@chakra-ui/react";
function Sidebar({ isOpen, onClose }) {
const [isLargerThan1024] = useMediaQuery("(min-width: 1024px)");

return (
isOpen={isOpen}
placement="left"
onClose={onClose}
variant={isLargerThan1024 ? "permanent" : ""}
>



Sidebar
{/* Sidebar content */}



);
}

Let’s break this down:

– We use the useMediaQuery hook to check if the screen width is greater than 1024px and store the result in isLargerThan1024 flexible.

– The Drawer the part gets i isOpen again onClose props to control its visibility and provide a way to close it.

– Conditionally set a different prop for Drawer based on screen size:

– If isLargerThan1024 is true (screen width is greater than 1024px), we set i variant to "permanent"which means the cabinet will always be visible.

– If isLargerThan1024 is false (screen width is less than 1024px), we set i variant to ""which means the cabinet will be a temporary overlay that can be opened and closed, automatic behavior.– The DrawerOverlay, DrawerContent, DrawerCloseButton, DrawerHeaderagain DrawerBody components are used to organize the drawer and provide accessibility features such as the close button and ARIA-appropriate roles.

Keep Checking

Chakra UI is a dynamic library that can increase your productivity when building React applications. Using its theme customization, responsive styles, automatic style tools, conditional rendering, and accessible components, you can create great looking links with minimal effort.

Remember, the key to mastering any tool is to test its capabilities, try it out in different ways, and find out what works best for your specific use case. The examples and explanations in this article should give you a solid foundation to build on.

About Ayrshare

Ayrshare is a social media API that allows you to publish posts, get analytics, manage comments, and send direct messages to social media directly from your platform. Read more in our social media API documentation.

Arthur K.

Founder of Gadget Tunes! A passionate content writer.. specializes in Marketing topics, technology, lifestyle, travel, etc.,

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button