Today I Learned

Implement mediaQuery helper for styled-component

April 01, 2021

styled component

Add breakpoint values to the global theme

import { DefaultTheme } from "styled-components";

export const theme: DefaultTheme = {
  breakpoint: {
    sm: "480px",
    md: "768px",
    lg: "1024px",
  },
};

Implement helper

export const mediaQueries = (key: "sm" | "md" | "lg") => {
  return (style: TemplateStringsArray, ...values: string[]) => {
    const styles = style
      .map((str, index) => `${str}${values[index] || ""}`)
      .join("");
    
    return `@media (min-width: ${theme.breakpoint[key]}) { ${styles} }`;
  };
};

Usage

const Wrapper = styled.div`
  background-color: red;  /* mobile */

  ${mediaQueries("md")`  /* tablet & desktop */
    background-color: blue;
  `}
`;

© 2025 - Written by Vuong Vu. Connect with me on LinkedIn.