javascriptcssreactjstailwind-css

How do I get Tailwind's active breakpoint in JavaScript?


I am building Tailwind with config file and including it in a React project.

I would like to get the active breakpoint value in JavaScript/React. How can I achieve the same?

 <div class="block  sm:hidden md:hidden lg:hidden xl:hidden">al</div>
  <div class="hidden sm:block  md:hidden lg:hidden xl:hidden">sm</div>
  <div class="hidden sm:hidden md:block  lg:hidden xl:hidden">md</div>
  <div class="hidden sm:hidden md:hidden lg:block  xl:hidden">lg</div>
  <div class="hidden sm:hidden md:hidden lg:hidden xl:block">xl</div>
</div>

The above shows the active breakpoints. But how do I get the same in JS without including any of the above markup?


Solution

  • Here's what I wrote in Typescript that returns the current breakpoint based on device width. You can place it in a standalone file and import the methods whenever needed in any file:

    import resolveConfig from 'tailwindcss/resolveConfig';
    import tailwindConfig from './tailwind.config'; // Fix the path
    
    const fullConfig = resolveConfig(tailwindConfig);
    
    export const getBreakpointValue = (value: string): number =>
      +fullConfig.theme.screens[value].slice(
        0,
        fullConfig.theme.screens[value].indexOf('px')
      );
    
    export const getCurrentBreakpoint = (): string => {
      let currentBreakpoint: string;
      let biggestBreakpointValue = 0;
      for (const breakpoint of Object.keys(fullConfig.theme.screens)) {
        const breakpointValue = getBreakpointValue(breakpoint);
        if (
          breakpointValue > biggestBreakpointValue &&
          window.innerWidth >= breakpointValue
        ) {
          biggestBreakpointValue = breakpointValue;
          currentBreakpoint = breakpoint;
        }
      }
      return currentBreakpoint;
    };
    
    

    Edit: in newer Typescript versions you have to add these two parameters to tsconfig.json under compilerOptions in order to be able import js files:

    "compilerOptions": {
      "allowJs": true,
      "allowsyntheticdefaultimports": true
    }
    

    Also, if you are on Angular and get the error that process is not defined, you have to add these lines to the end of your polyfills.ts file (you have to install the process package of course):

    import * as process from 'process';
    window['process'] = process;