Detecting Breakpoints in React Using Chakra UI

Hero image for Detecting Breakpoints in React Using Chakra UI. Image by Rubenz Arizta.
Hero image for 'Detecting Breakpoints in React Using Chakra UI.' Image by Rubenz Arizta.

The project I'm currently working on makes heavy use of Chakra UI, an opensource library of reusable React components built using the Emotion CSS-in-JS library and the styledsystem design system.

It is fair to say that it has been a fairly steep learning curve, but one of the things I've come to be very impressed with is the useBreakpoint hook it exposes. When combined with ThemeProvider, it allows the application to respond and adapt to different screen sizes very easily.

The hook returns a boolean value which indicates whether the current screen size matches a specified breakpoint or not.

To use the useBreakpoint hook, you first need to install the @chakraui/react package, after which you can import the hook into your component like this:

import { useBreakpoint } from '@chakra-ui/react'

And use it like this:

const isSmall = useBreakpoint('sm');

The hook accepts a breakpoint argument, which by default can be one of the following values: xs, sm, md, lg, xl, or 2xl. By default, these correspond to:

  • xs: 0px and up
  • sm: 640px and up
  • md: 768px and up
  • lg: 1024px and up
  • xl: 1280px and up
  • 2xl: 1536px and up

As the hook returns a simple boolean, you can then chain calls together to create fairly complex conditional rendering logic:

const isSmall = useBreakpoint('sm');const isMedium = useBreakpoint('md');const isLarge = useBreakpoint('lg');if (isSmall) {  return <p>The screen is small!</p>;} else if (isMedium) {  return <p>The screen is medium!</p>;} else if (isLarge) {  return <p>The screen is large!</p>;} else {  return <p>The screen is extra large!</p>;}

Customising the Default Breakpoints

It's also very straightforward to customize the default breakpoints used in the useBreakpoint hook, you can use the theme object provided by the ThemeProvider component from @chakraui/react.

For example:

import { ThemeProvider } from '@chakra-ui/react';const theme = {  breakpoints: {    sm: '400px',    md: '600px',    lg: '950px',    xl: '1100px',  },};function App() {  return (    <ThemeProvider {...theme}>      {/* Your application components go here */}    </ThemeProvider>  );}

And that's it! With the useBreakpoint hook, you can easily create responsive layouts in your Chakra UI application by detecting screen sizes and adapting the content accordingly.

Obviously, there are also plenty of other ways to achieve this if you don't happen to have inherited a project that's already using Chakra!


Categories:

  1. Chakra UI
  2. Development
  3. Front‑End Development
  4. React
  5. Responsive Development