Problem with arbitrary values on Tailwind with React

Viewed 8273

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

3 Answers

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.

The actual solution as @Dennis Martinez mentioned in a comment is to move truly dynamic styles out of the classes and to inline styles.

This is wrong:

const padding = 80;
<div className=`p-[${padding}%]`>
  Some Content
</div>

Instead use inline styling:

const padding = 80;
<div style={{padding: `${padding}%`}}>
  Some Content
</div>

Include mode: 'jit' in tailwind config file

Related