25

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?

8 Answers 8

41

From the tailwind docs, you can import your config from the tailwindcss node module:

import resolveConfig from 'tailwindcss/resolveConfig'
import tailwindConfig from './tailwind.config.js'

const fullConfig = resolveConfig(tailwindConfig)

fullConfig.theme.width[4]
// => '1rem'

fullConfig.theme.screens.md
// => '768px'

fullConfig.theme.boxShadow['2xl']
// => '0 25px 50px -12px rgba(0, 0, 0, 0.25)'

As you can see above, you can get your breakpoints by referencing fullConfig.theme.screens.{breakpoint}. You should be able to compare this to your current screen width using javascript.

Find the official tailwind description here.

4
  • 2
    I can't import tailwindConfig from './tailwind.config.js' if I am using a react project is there any alternative to that? Jan 2, 2022 at 6:21
  • 2
    @S_coderX451 react has nothing to do with being able to import from tailwind.config.js if you've ran npx tailwindcss init at the root of your projects directory, you will have a tailwind.config.js file. You have to make sure the path i.e. '../../tailwind.config.js' is correct. If you're importing in file x.js, and x.js is in {projectRoot}/components/x.js. The import will be import tailwindConfig from '../tailwind.config.js'. Apr 30, 2022 at 22:26
  • 1
    If you are having trouble importing the config file in Vite check out this tutorial: lobotuerto.com/notes/import-tailwind-config-in-vite
    – zenw0lf
    Sep 18, 2022 at 0:44
  • did not work, only the extended styles showed up in the fullConfig variable Sep 13 at 3:22
14

Here is a little hook for those using TypeScript 4.5+. It's based on the useMediaQuery hook from the react-responsive package. Modify it as you please!

import { useMediaQuery } from 'react-responsive';
import { theme } from '../../tailwind.config'; // Your tailwind config

const breakpoints = theme.screens;

type BreakpointKey = keyof typeof breakpoints;

export function useBreakpoint<K extends BreakpointKey>(breakpointKey: K) {
  const bool = useMediaQuery({
    query: `(min-width: ${breakpoints[breakpointKey]})`,
  });
  const capitalizedKey = breakpointKey[0].toUpperCase() + breakpointKey.substring(1);
  type Key = `is${Capitalize<K>}`;
  return {
    [`is${capitalizedKey}`]: bool,
  } as Record<Key, boolean>;
}

Inside your component, use it like this

const { isSm } = useBreakpoint('sm');
const { isMd } = useBreakpoint('md');
const { isLg } = useBreakpoint('lg');
return (
      <div>
        {isSm && (
          {/* Visible for sm: (min-width: 640px) */}
          <div>Content</div>
        )}

        {isMd && (
          {/* Visible for md: (min-width: 768px) */}
          <div>Content</div>
        )}
      </div>
  );
1
  • 6
    If your tailwind config is not complete and only extends the default config you need to resolve the complete config with: import resolveConfig from "tailwindcss/resolveConfig"; import tailwindConfig from "../../tailwind.config"; const fullConfig = resolveConfig(tailwindConfig); and access the breakpoints: const breakpoints = fullConfig.theme.screens;
    – kuzdogan
    Aug 1, 2022 at 19:38
12

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;
4
  • 2
    Thanks for that snippet. It doesn't work properly since getBreakpointValue is returning a string and the >= comparision between strings and numbers made weird things. I solved it with const getBreakpointValue = (value: string): number => parseInt(fullConfig.theme.screens[value].replace('px', ''), 10);
    – Frébo
    Dec 29, 2020 at 16:12
  • Sadly, in Angular this doesn't work. It's quite frustrating how it's not possible to access css variables in angular. Jan 10, 2022 at 15:15
  • I'm getting no luck even after adding allowJs Internal server error: Failed to resolve import "./tailwind.config" from "src/constants/layout.ts". Does the file exist? Feb 15, 2022 at 23:49
  • 1
    @SuperUberDuper you should fix the path based on your folder structure
    – Sinandro
    Feb 20, 2022 at 6:18
6

I've combined the other solutions to achieve what I need.

/**
 * @desc The 'useBreakpoint()' hook is used to get the current 
 *       screen breakpoint based on the TailwindCSS config.
 *
 * @usage
 *    import { useBreakpoint } from "@/hooks/useBreakpoint";
 *
 *    const { isAboveSm, isBelowSm, sm } = useBreakpoint("sm");
 *    console.log({ isAboveSm, isBelowSm, sm });
 *
 *    const { isAboveMd } = useBreakpoint("md");
 *    const { isAboveLg } = useBreakpoint("lg");
 *    const { isAbove2Xl } = useBreakpoint("2xl");
 *    console.log({ isAboveMd, isAboveLg, isAbove2Xl });
 *
 * @see https://stackoverflow.com/a/76630444/6543935
 * @requirements npm install react-responsive
 */
import { useMediaQuery } from "react-responsive";
import resolveConfig from "tailwindcss/resolveConfig";
import { Config, ScreensConfig } from "tailwindcss/types/config";

import tailwindConfig from "@/tailwind.config"; // Your tailwind config

const fullConfig = resolveConfig(tailwindConfig as unknown as Config);

const breakpoints = fullConfig?.theme?.screens || {
    xs: "480px",
    sm: "640px",
    md: "768px",
    lg: "1024px",
    xl: "1280px",
};

type BreakpointKey = keyof ScreensConfig;

export function useBreakpoint<K extends string>(breakpointKey: K) {
    const breakpointValue = breakpoints[breakpointKey as BreakpointKey];
    const bool = useMediaQuery({
        query: `(max-width: ${breakpointValue})`,
    });
    const capitalizedKey = breakpointKey[0].toUpperCase() + breakpointKey.substring(1);

    type KeyAbove = `isAbove${Capitalize<K>}`;
    type KeyBelow = `isBelow${Capitalize<K>}`;

    return {
        [breakpointKey]: Number(String(breakpointValue).replace(/[^0-9]/g, "")),
        [`isAbove${capitalizedKey}`]: !bool,
        [`isBelow${capitalizedKey}`]: bool,
    } as Record<typeof breakpointKey, number> & Record<KeyAbove | KeyBelow, boolean>;
}

Here is an example of usage within Next.js 13 with App router:

"use client";

import React, { useEffect } from "react";

import { useBreakpoint } from "@/hooks/useBreakpoint";

const Nav: React.FC = () => {
    const { isAboveSm, isBelowSm, sm } = useBreakpoint("sm");

    useEffect(() => {
        console.log({ isAboveSm, isBelowSm, sm });
    });

   return (
        <> ... </>
   );
};

Console output (on screen width larger than 640px):

{ isAboveSm: true, isBelowSm: false, sm: 640 }

In case Next.js complains the Server side rendering doesn't match with the Client side, you can use useLayoutEffect() hook:

const [isBwXs, setIsBwXs] = React.useState<boolean>(false);
const { isBelowXs } = useBreakpoint("xs");

useLayoutEffect(() => {
    setIsBwXs(isBelowXs);
}, [isBelowXs]);

Note: Depending on your configuration you may need to change the tailwind.config file from module.exports = {...} to something like:

const tailwindConfig: import("tailwindcss").Config = {...};
export default tailwindConfig;
2
  • 1
    This worked perfectly on NextJS 13 !
    – rogeliorv
    Jul 8 at 15:21
  • I second this. Absolutely fab!
    – Lauro235
    Aug 21 at 19:41
4

If anyone is looking for an approach that doesn't use tailwind's config, you can achieve this by using tailwind's breakpoint system to control the visibility of several 0x0 divs, and test for the visibility of those divs to determine the current active breakpoint.

For example, you might embed several divs of size 0 in your body like so:

<div id="breakpoint-sm" class="hidden sm:block md:hidden lg:hidden xl:hidden 2xl:hidden w-0 h-0"></div>
<div id="breakpoint-md" class="hidden sm:hidden md:block lg:hidden xl:hidden 2xl:hidden w-0 h-0"></div>
<div id="breakpoint-lg" class="hidden sm:hidden md:hidden lg:block xl:hidden 2xl:hidden w-0 h-0"></div>
<div id="breakpoint-xl" class="hidden sm:hidden md:hidden lg:hidden xl:block 2xl:hidden w-0 h-0"></div>
<div id="breakpoint-2xl" class="hidden sm:hidden md:hidden lg:hidden xl:hidden 2xl:block w-0 h-0"></div>

Then, you can write a function that looks for these elements and checks if they are visible via each element's offsetParent property:

const getCurrentBreakpoint = (): string => {
    const breakpointUnknown: string = 'unknown';
    const breakpointSM: string | null = document.getElementById('breakpoint-sm')?.offsetParent === null ? null : 'sm';
    const breakpointMD: string | null = document.getElementById('breakpoint-md')?.offsetParent === null ? null : 'md';
    const breakpointLG: string | null = document.getElementById('breakpoint-lg')?.offsetParent === null ? null : 'lg';
    const breakpointXL: string | null = document.getElementById('breakpoint-xl')?.offsetParent === null ? null : 'xl';
    const breakpoint2XL: string | null = document.getElementById('breakpoint-2xl')?.offsetParent === null ? null : '2xl';
    const breakpoint = breakpointSM ?? breakpointMD ?? breakpointLG ?? breakpointXL ?? breakpoint2XL ?? breakpointUnknown;
    return breakpoint;
};

Now you can test for the current breakpoint string to perform some logic:

const breakpoint = getCurrentBreakpoint();
const desktopBreakpoints: string[] = ['sm', 'md', 'lg', 'xl'];
if (desktopBreakpoints.includes(breakpoint)) {
   // On Desktop (in Tailwind's eyes)
} else {
   // On Mobile (in Tailwind's eyes)
}

You'll need to ensure whatever breakpoints you have Tailwind using are both applied to a 0x0 div somewhere in your document that you can obtain, and to check for those breakpoints in your getCurrentBreakpoint() function. But this gets the job done without needing to inspect Tailwind's config and uses Tailwind's actual breakpoint system to determine which is currently active.

1
  • 1
    Nice hack actually! This may not look so clean but I like the idea. May 9 at 7:22
3

For this purpose I use this peace of code :

import { theme } from '../../tailwind.config';

export function getCurrentBreakpoints() {
    return Object.keys(theme.screens).find((key) => window.innerWidth > theme.screens[key]);
}
3

I can resolve this in React like this:

{/* MOBILE FIRST */}
<div className="sm:hidden">
  <Component breakpoint="mobile" />
</div>

{/* SMALL */}
<div className="hidden sm:block md:hidden">
  <Component breakpoint="sm" />
</div>


{/* MEDIUM */}
<div className="hidden md:block lg:hidden">
  <Component breakpoint="md" />
</div>


{/* LARGE */}
<div className="hidden lg:block xl:hidden">
  <Component breakpoint="xl" />
</div>

{/* EXTRA LARGE */}
<div className="hidden xl:block 2xl:hidden">
  <Component breakpoint="xl" />
</div>

and in my Component.jsx

import React from 'react'

const Component = (prop) => {
  const { breakpoint } = prop;
  return (
    <div>{breakpoint}</div>
  )
}
export default Component
1
  • The number of events on dom would be high. Imagine a table rows of 1000 with responsiveness
    – Prakash S
    Jun 24, 2022 at 15:33
0

Using Nuxt3, I adapted the accepted answer to js.

import tailwindConfig from '~/tailwind.config';
import resolveConfig from 'tailwindcss/resolveConfig';

const { theme: { screens } } = resolveConfig(tailwindConfig);

const getActiveBreakpoint = () => {
    /* Sort the breakpoints based on their dimensions in descending order */
    const sorted = Object.entries(screens).sort((x, y) => parseInt(y[1]) - parseInt(x[1]));

    /* Find the first instance where the current width is higher or equal to a breakpoint */
    const bp = sorted.find((s) => window.innerWidth >= parseInt(s[1]));

    /* if no breakpoint is found, it is a mobile screen */
    if (!bp) return "mb"
    else return bp[0]
}

remember to call getActiveBreakpoint() in onMounted().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.