I want to use the tailwind theme in my react component. For this purposes i made this:
import theme from "tailwindcss/defaultTheme";
console.log(theme)
Also, i created the tailwind.config.js file where i added new changes to the theme.
Doing this i encountered an issue, because the values from console.log(theme) are default tailwind values even if i overrode them.
How to get the updated values from tailwind theme?
let's assume we have the following defined in our tailwind.config.js:
const colors = require('tailwindcss/colors')
module.exports = {
theme: {
colors: {
white: colors.slate[50],
dark: colors.slate[900],
},
},
// content: ...
// plugins: ...
}
now we can access the property white after importing the config file
import { theme } from './tailwind.config.js'
const color = theme.colors['white']
since tailwind JIT can't handle dynamic class names, we can create our own getters to use tailwind defaults and our config
import { spacing as defaultSpacing } from 'tailwindcss/defaultTheme'
import { theme } from '../tailwind.config.js' // path may vary
export const getThemeColor = (color) => theme.colors[color]
export const getTailwindSpacing = t => defaultSpacing[`${t}`]
and use it everywhere in the code with the usual style attribute
export const SomeComponent = () => {
const someCalculatedValue = 2 * 2
return (
<div style={{
right: tailwindSpacing(someCalculatedValue)
backgroundColor: getThemeColor('white')
}}>
some content
</div>
)
}
import { spacing as defaultSpacing } from 'tailwindcss/defaultTheme'
import { theme } from '../tailwind.config.js' // path may vary
export const getThemeColor = (color: string) => theme.colors[color]
export const getTailwindSpacing = (spacing: number) => {
const number = `${spacing}` as keyof typeof defaultSpacing
return defaultSpacing[number]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With