Search code examples
javascriptreactjstailwind-css

Problem with arbitrary values on Tailwind with React


I'm trying to make a react component that changes the width from a parameter but it's doesn't work and I don't know why.

function Bar() {
    
    const p =80

    const style = `bg-slate-500 h-8 w-[${p.toFixed(1)}%]`

    console.log(style)

    return (
        <div className=' h-8 w-full'>
            <div className={`bg-slate-500 h-8 w-[${p}%]`}>
            </div>
        </div>
    )
}
export default Bar

With this code I get a full-size bar, but if I use a strict String with 80.0 it works fine


Solution

  • The other answers are wrong. In Tailwind V3 JIT is included and you won't need to set mode to jit anymore. And even in Tailwind V2 the posted code wouldn't work.

    Following the docs, you must avoid string interpolation and use complete class names.

    This is wrong:

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

    Instead use Complete class names:

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

    What about using inline styles?

    You may be tempted to use inline styles, but remember Content Security Policies are increasingly under scrutiny to disallow unsafe inlines. Any inline style or script could in theory be injected with unintended content. Furthermore, the whole point to Tailwind is to generate CSS at build time, so you'd be working around it and might as well not even be using it in this case.