Last active
March 20, 2023 12:48
-
-
Save james2doyle/c1306ace82cfe9e22a4ecfff13c6595b to your computer and use it in GitHub Desktop.
Find out if a tailwind screen value matches the current window
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* 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