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
  • 2
    Does this answer your question? React Js conditionally applying class attributes Commented Apr 23, 2020 at 9:04
  • Yes, it does Thanks. Commented Apr 23, 2020 at 15:15

2 Answers 2

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>
    )
    
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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

Comments

Your Answer

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