29

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

4
  • 4
    You're using arbitrary values incorrectly. Have a look at the first paragraph under Dynamic values v2.tailwindcss.com/docs/… your classes need to exist as complete strings for Tailwind to detect them correctly. Commented Jan 4, 2022 at 20:41
  • You can use css variables in some caese text-[color:var(--your-val)] and that pass it through style={ { '--your-var': '#fff' }} Commented Jan 18, 2022 at 0:46
  • What is your filename? Including extension Commented May 22, 2022 at 21:32
  • 2
    Newer docs for V3+: tailwindcss.com/docs/content-configuration#dynamic-class-names Commented Mar 30, 2023 at 21:44

7 Answers 7

32

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.

Sign up to request clarification or add additional context in comments.

9 Comments

Why is the first approach wrong?
@sir v2.tailwindcss.com/docs/… , also applies to V3 unless they changed it recently
You still need to manually enable jit in tailwind.config as of today. The thing OP did wrong was use string concatenation to build the class, as described in the docs under "Dynamic Values" here. v2.tailwindcss.com/docs/just-in-time-mode#overview
@sir because Tailwind is generating classes at build time and won't be aware of the value of padding, so the class p-[80%] won't be exported. Nevertheless, if you add p-[80%] in the safelist array, Tailwind will then add this class at build time. But there is no point on doing this because it would only work for padding = 80;
@MaximeLechevallier but inline styles are insecure aren't they? For instance, CORS policy can only permit them with unsafe inline, which is really not always an option... Also, this completely defeats the purpose of tailwind by working around its API doesn't it?
|
32

I had exactly the same problem as you.

const p =80
<div className={`bg-slate-500 h-8 w-[${p}%]`}>

The above code set "w-[${p}%]" as "w-80%" dynamically on the server side. However Tailwind has no ability to deal with the arbitrary values computed dynamically.

The official Tailwind docs say;

https://v2.tailwindcss.com/docs/just-in-time-mode#arbitrary-value-support

To work around this problem, we need to use style attribute like following in which we are not able to use TailwindCSS anymore😅;

<div
  style={{width: `${p}%`}} 
  className={`bg-slate-500 h-8`}>

See the discussions on GitHub

I hope it helps you a lot.

Comments

3

I ran into a similar issue building a site with Astro & Tailwind.

The solution I discovered was to use the 'safelist' feature that allows you to define certain classes that will be force-compiled, regardless of whether or not they are found when scanning the specified content locations in the tailwind.config.cjs file.

An example of the code I used to fix my situation:

module.exports = {
content: ["./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}"],
Adding a safelist and classes to it:
safelist: ["lg:grid-cols-[1fr_4fr]", "lg:grid-cols-[1fr_3fr_1fr]"],
...

Here's a link to the relevant area in the Tailwind documentation.

1 Comment

Honestly, this should be the accepted answer
1

in tailwind.config.js add mode: 'jit'.

I would suggest https://v2.tailwindcss.com/docs/just-in-time-mode to learn more.

e.g:

module.exports = {
   //other options
   mode: 'jit',
}

1 Comment

How would you handle templates or liquid engines for instance Shopify theme or email templating?
1

If your p's value is a constant that will be used across the app, you can instead define it in your tailwind.config.js file like this.

theme: {
 extend: {
  spacing: {
    "p-value": "80%",
  },
 }, 
}

Then you can modify your code to this.

<div className="bg-slate-500 h-8 w-p-value">

Comments

1

in React with tailwind Styles follow this pattern:

<div className={`bg-red-500 flex w-[70%] h-[70%]`} style={{boxShadow: `${horizantal}px ${vertical}px ${blur}px ${spraied}px ${color}`}}

Comments

-1

Include mode: 'jit' in tailwind config file

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.