Background Color is not displayed on my button in Vite React and tailwind CSS

98 Views Asked by At

This is my Button.jsx file:

import React from 'react'

function Button({ btnColor = "white" }) {
  const bgColor = `bg-${btnColor.toLowerCase()}-500`
  return (
    <button className={`${bgColor}`}>{btnColor}</button> 
  )
}

export default Button

I tried multiple times to identify my problem. The button color is not changing and is fixed while using variables, but working fine while hardcoded ie. directly passing the value, but the output of bgColor is fine and is a String.

I don't see any reason to not be able to run.

1

There are 1 best solutions below

0
On

As per the documentation:

The most important implication of how Tailwind extracts class names is that it will only find classes that exist as complete 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 complete class names

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

You could:

  • Have the entire class in the variable you pass to className like:
    function Button({ btnColor = "bg-white-500" }) {
      return (
        <button className={btnColor}>{btnColor}</button> 
    
  • Have a dictionary for btnColor to Tailwind class names:
    function Button({ btnColor = "white" }) {
      const DICTIONARY = {
        white: 'bg-white-500',
        // …
      };
      return (
        <button className={DICTIONARY[btnColor]}>{btnColor}</button> 
    
  • safelist the classes, if you have a limited number of known colors:
    module.exports = {
      safelist: [
        { pattern: /^bg-(white|red|…)-500$/ },
        // …
      ],
      // …
    ];