@digitaliseringsbyran/tailwindcss-screens-in-dom
v0.1.1
Published
Expose the active tailwind screen to the DOM.
Downloads
23
Readme
tailwindcss-screens-in-dom
Expose the active tailwind screen (like sm
, md
) in body:before
, allowing you to use the value in Javascript. Read more
Installation
$ npm install @digitaliseringsbyran/tailwindcss-screens-in-dom --save-dev
Usage
Add the plugin to the plugins
array in your tailwind config.
plugins: [
// ...
require('@digitaliseringsbyran/tailwindcss-screens-in-dom')()
]
Options
You can pass an object to override the default settings.
// Default options
plugins: [
require('@digitaliseringsbyran/tailwindcss-screens-in-dom')({
noScreen: 'xs' // Viewports below the smallest defined screen.
})
]
Access the active screen in Javascript
Accessing the value in plain Javascript is explained here.
React
A example hook that returns the active screen as a string:
useTailwindScreen.js
import { useState, useEffect } from 'react'
export default () => {
const isClient = typeof window === 'object'
function getScreen() {
return window
.getComputedStyle(document.querySelector('body'), ':before')
.getPropertyValue('content')
.replace(/"|'/g, '')
}
const initialState = isClient ? getScreen() : ''
const [screen, setScreen] = useState(initialState)
useEffect(() => {
if (!isClient) {
return false
}
function handleResize() {
setScreen(getScreen())
}
window.addEventListener('resize', handleResize)
return () => window.removeEventListener('resize', handleResize)
}, [])
return screen
}
Component
import React from 'react'
import useTailwindBreakpoint from './useTailwindBreakpoint'
const ActiveScreen => {
const screen = useTailwindBreakpoint()
return (
<span>{screen}</span>
)
}
export default ActiveScreen