Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use tailwind css theme inside react component

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?

like image 259
Asking Avatar asked Aug 10 '26 09:08

Asking


1 Answers

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']

Bonus

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>
  )
}

Typescript Version

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]
}
like image 162
Richard Avatar answered Aug 11 '26 23:08

Richard