Search code examples
cssresponsive-designantd

How to make custom component style for different screen sizes with Ant Design


I am trying to figure out how can I check what is my current screen size and based on that set a specific width/height with ant design. With the last version 5+ of antd I am using design token, not less css.

More specifically I am looking for a way to do exactly what the Grid component is doing, I want to just pass information for xs, sm, md, lg, xl, xxl that should scale my component. I could not find how this should be done in the documentation.


Solution

  • You can use useBreakpoint hook and a custom js/ts file to handle your styles.

    /**
     * component.js/ts
     */
    import Styles from "path/to/styles";
    
    function Index() {
      const S = Styles();
    
      return <Input style={S.Input} />;
    }
    
    /**
     * styles.js/ts
     */
    import { CSSProperties } from "react";
    import { Grid } from "antd";
    
    type StylesType = {
      Input: CSSProperties;
      OtherComponent: CSSProperties;
    };
    
    const { useBreakpoint } = Grid;
    
    function Styles(): StylesType {
      const breakpoints = useBreakpoint();
    
      const Input: CSSProperties = {
        width: (() => {
          // you can now use any breakpoint and 
          // return different styles based
          if (breakpoints.xs) return "100%";
          if (breakpoints.sm) return "50%";
          if (breakpoints.md) return "25%";
          if (breakpoints.lg) return "10%";
          // default style
          return "100px";
        })()
      };
    
      const OtherComponent: CSSProperties = (() => {
        if (breakpoints.xs) return {
          width: '100%',
          color: 'red'
        }
    
        if(breakpoints.sm) return {
          width: '100px',
          color: 'blue'
        }
      })()
    
      return {
        Input,
        OtherComponent
      };
    }
    
    export default Styles;
    

    Here is a working codesandbox example.

    Hope this helps