How do I get tailwinds 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 breakpoint. but how do i get the same in js without including any of the above markup.?
Solution 1:
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.
See more here.
Solution 2:
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;