Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Last active March 20, 2023 12:48
Show Gist options
  • Save james2doyle/c1306ace82cfe9e22a4ecfff13c6595b to your computer and use it in GitHub Desktop.
Save james2doyle/c1306ace82cfe9e22a4ecfff13c6595b to your computer and use it in GitHub Desktop.
Find out if a tailwind screen value matches the current window
/**
*
* Find out if a tailwind screen value matches the current window
*
* @param {string} screen
*
* @return {Object|Boolean}
*/
export const screenIs = (screen = '') => {
// "Theme" is an alias to where you keep your tailwind.config.js - most likely your project root
const screens = require('Theme/tailwind.config.js').theme.extend.screens;
// create a keyed object of screens that match
const matches = Object.entries(screens).reduce((results, [name, size]) => {
const mediaQuery = typeof size === 'string' ? `(min-width: ${size})` : `(max-width: ${size.max})`;
results[name] = window.matchMedia(mediaQuery).matches;
return results;
}, {});
// show all matches when there is no screen choice
if (screen === '') {
return matches;
}
// invalid screen choice
if (!screens[screen]) {
console.error(`No match for "${screen}"`);
return false;
}
return matches[screen];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment