最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why can't I pass variable as a className to tailwind-css? - Stack Overflow

programmeradmin1浏览0评论

I am trying to pass a context variable as a value to tailwind className in react. As per tailwind documentation bg-[hex-val] is used to pass custom color codes to background color.

I'm using Template literals to pass context variable as value.

NavBar.js

import { useContext } from 'react';
import { AiOutlineMenu } from 'react-icons/ai';
import ThemeToggle from './ThemeToggle';
import ThemeContext from '../context/ThemeContext';



const NavBar = () => {
    const { colors } = useContext(ThemeContext); 


    return <div className="w-screen h-46 bg-secondary-dark grid grid-cols-6 gap-4 content-center">
        
        {//below line is not working}

        <p className={`bg-[${colors.secondary}] text-text-white`}>Some words</p>
        <AiOutlineMenu style={{color:"white",fontSize:"1.5rem"}} className='ms-4 place-self-start col-span-5 '/>
        <ThemeToggle />
      
    </div>
}

export default NavBar;

ThemeContext.js

import { createContext,useState } from "react"

const ThemeContext = createContext();

const ThemeProvider = ({ children })=>{

    const [darkTheme, setTheme] = useState(true);
    
    const colors = {
        primary: darkTheme ? "#282828" : "#E8E8E8",
        secondary: darkTheme ? "#FFFFFF" : "#FFFFFF",
        secondary2: darkTheme ? '#232323' : '#ECECEC',
        card: darkTheme ?'#383838' : 'F3EFEF',
        buttons: darkTheme ? '#504D4D' : '#C0C0C0',
        buttonActive: darkTheme ? '#A9A9A9' : '#828282'
    }

    const handleTheme = (themeParam)=>{
        setTheme(themeParam);
    }
    return<>
            <ThemeContext.Provider value={{darkTheme, handleTheme, colors}}>
                {children}
            </ThemeContext.Provider>
        </>
}

export {ThemeProvider};
export default ThemeContext;

I have tried using classNames npm package to bine context variable and other classnames but no luck!

I am trying to pass a context variable as a value to tailwind className in react. As per tailwind documentation bg-[hex-val] is used to pass custom color codes to background color.

I'm using Template literals to pass context variable as value.

NavBar.js

import { useContext } from 'react';
import { AiOutlineMenu } from 'react-icons/ai';
import ThemeToggle from './ThemeToggle';
import ThemeContext from '../context/ThemeContext';



const NavBar = () => {
    const { colors } = useContext(ThemeContext); 


    return <div className="w-screen h-46 bg-secondary-dark grid grid-cols-6 gap-4 content-center">
        
        {//below line is not working}

        <p className={`bg-[${colors.secondary}] text-text-white`}>Some words</p>
        <AiOutlineMenu style={{color:"white",fontSize:"1.5rem"}} className='ms-4 place-self-start col-span-5 '/>
        <ThemeToggle />
      
    </div>
}

export default NavBar;

ThemeContext.js

import { createContext,useState } from "react"

const ThemeContext = createContext();

const ThemeProvider = ({ children })=>{

    const [darkTheme, setTheme] = useState(true);
    
    const colors = {
        primary: darkTheme ? "#282828" : "#E8E8E8",
        secondary: darkTheme ? "#FFFFFF" : "#FFFFFF",
        secondary2: darkTheme ? '#232323' : '#ECECEC',
        card: darkTheme ?'#383838' : 'F3EFEF',
        buttons: darkTheme ? '#504D4D' : '#C0C0C0',
        buttonActive: darkTheme ? '#A9A9A9' : '#828282'
    }

    const handleTheme = (themeParam)=>{
        setTheme(themeParam);
    }
    return<>
            <ThemeContext.Provider value={{darkTheme, handleTheme, colors}}>
                {children}
            </ThemeContext.Provider>
        </>
}

export {ThemeProvider};
export default ThemeContext;

I have tried using classNames npm package to bine context variable and other classnames but no luck!

Share Improve this question asked Jun 22, 2023 at 19:44 PradeepPradeep 411 silver badge4 bronze badges 1
  • Instead of declaring class names, you can use CSS variables to declare Tailwind class names. The native CSS class can also be prepared with the CSS variable name. The CSS variable can then be manipulated at runtime using JavaScript. For more details, see @dogukan's answer to the "Using TailwindCSS and JS variables" question. – rozsazoltan Commented Sep 4, 2023 at 12:28
Add a ment  | 

2 Answers 2

Reset to default 7

As per the documentation:

The most important implication of how Tailwind extracts class names is that it will only find classes that exist as plete unbroken strings in your source files.

If you use string interpolation or concatenate partial class names together, Tailwind will not find them and therefore will not generate the corresponding CSS:

Don’t construct class names dynamically

<div class="text-{{ error ? 'red' : 'green' }}-600"></div>

In the example above, the strings text-red-600 and text-green-600 do not exist, so Tailwind will not generate those classes. Instead, make sure any class names you’re using exist in full:

Always use plete class names

<div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>

You could consider using full class names in definitions, like:

const colors = {
  // …
  secondary: darkTheme ? "bg-[#FFFFFF]" : "bg-[#FFFFFF]",
  // …
}:
<p className={`${colors.secondary} text-text-white`}>

Or you could look at using the style attribute like:

<p className="text-text-white" style={{ backgroundColor: colors.secondary }}>

As a last resort, if you need to construct class names dynamically, make sure to safelist possible values in the tailwind.config.js to force Tailwind's process to include them in the final stylesheet

<div class="text-{{ error ? 'red' : 'green' }}-600"></div>
/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    './pages/**/*.{html,js}',
    './ponents/**/*.{html,js}',
  ],
  safelist: [
    'text-red-600',
    'text-green-600'
  ]
  // ...
}

You could also use a pattern to match classes:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    './pages/**/*.{html,js}',
    './ponents/**/*.{html,js}',
  ],
  safelist: [
    {
      pattern: /bg-(red|green)-600/,
    },
  ]
  // ...
}

There is more in doc: https://tailwindcss./docs/content-configuration#safelisting-classes

发布评论

评论列表(0)

  1. 暂无评论