How to add dynamic TailwindCSS classes to DOM elements in React

10,646
  • You can use the new ES6 "template strings".

  • This is a simple React component that has disabled the (-) button when counter <= 0

  • .pointer-even-none is the tailwindCSS class that renders the disable button

    const [count, setCount] = useState(0);
    
    return (
      <Fragment>
           {/* button Substract with styles tailwind*/}
          <button className={`p-2 ${count <= 0 ? 'opacity-50 pointer-events-none': 'bg-red-700'}`} 
                  onClick={() => setCount( count - 1 )}>
                  Substract
          </button>
    
          {/* Counter */}
          <span className="p-2">{ count }</span>
    
          {/* button Add whit styles tailwind*/}
          <button className="p-2 bg-green-700"
                  onClick={() => setCount(count + 1 )}>
                  Add
          </button>
      </Fragment>
    )
    
Share:
10,646
mpgbk
Author by

mpgbk

Working as Javascript Full Stack Developer.

Updated on June 12, 2022

Comments

  • mpgbk
    mpgbk almost 2 years

    I am new to TailWindCSS, I want to add enable/disable style to a Button element. How can I add disabled specific styles/class(i.e let's say I need to add "opacity-50 cursor-not-allowed") to the button conditionally?

        <button
              className="bg-blue-500 hover:bg-blue-400 text-white font-bold py-2 px-4 border-b-4 border-blue-700 hover:border-blue-500 rounded mr-3"
              disabled={!globalContext.users.length > 0}
              onClick={handleClearResultsClick}
            >
              Clear Results
        </button>