4

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>
  • 2
    Does this answer your question? [React Js conditionally applying class attributes](https://stackoverflow.com/questions/30533171/react-js-conditionally-applying-class-attributes) – Remul Apr 23 '20 at 09:04
  • Yes, it does Thanks. –  Apr 23 '20 at 15:15

2 Answers2

8
  • 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>
    )
    
  • if `opacity-50` class is not used anywhere else in the project. it will not be available in compiled code. from my testing, it will not be available in compiled CSS and it will not work. let me know if there is a workaround for this. If your dynamic classes are used else where you should be ok. – m-farhan Jun 19 '22 at 23:51
1
classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'

// lots of arguments of various types
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'

// other falsy values are just ignored
classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'

You can use this light weight library classname

https://www.npmjs.com/package/classnames

It will keep things tidy

m-farhan
  • 1,436
  • 13
  • 14