0

I'm trying to use a media query breakpoint inside Chakra UI global styles.

This is what I tried but you can't use template literals for property names:

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

const theme = extendTheme({
  styles: {
    global: (props) => ({
      `@media screen and (max-width: ${props.theme.breakpoints.sm})`: {
        div: {
          border: "1px solid",
        },
      },
    }),
  }
});

function App() {
  return (
    <ChakraProvider theme={theme}>
      <div>Hello world!</div>
    </ChakraProvider>
  );
}

export default App;

I also tried concatenating the property name but it's no valid either:

const theme = extendTheme({
  styles: {
    global: (props) => ({
      "@media screen and (max-width: " + props.theme.breakpoints.sm + ")": {
        div: {
          border: "1px solid",
        },
      },
    }),
  }
});

The only way around it I found is hardcoding the value instead of reading it from props.theme:

const theme = extendTheme({
  styles: {
    global: {
      "@media screen and (max-width: 30em)": {
        div: {
          border: "1px solid",
        },
      },
    },
  }
});

Is there any other way around this? I couldn't find this scenario in the docs.

Camilo
  • 6,504
  • 4
  • 39
  • 60

1 Answers1

1

You can access dynamic property name using bracket notation.

const theme = extendTheme({
  styles: {
    global: (props) => ({
       [`@media screen and (max-width: ${props.theme.breakpoints.sm})`] : {
        div: {
          border: "1px solid",
        },
      },
    }),
  }
}); 
Camilo
  • 6,504
  • 4
  • 39
  • 60