42

I'd like to set the disabled attribute on a Button based on component's state, something like this:

render() {
  return (
    <button type="button" {this.state.submitting ? 'disabled' : ''} 
      onClick={ this.handleSubmit }>Submit</button>
    );
}

At the moment I get an Unexpected token error on the opening {, what am I missing?

0

4 Answers 4

74

You can set disabled property through boolean value, like this

<button
  type="button"
  disabled={this.state.submitting}
  onClick={this.handleSubmit}
>
  Submit
</button>

Example

2
  • 10
    Ahh, yes of course because it's JSX disabled=false will work, unlike HTML which will just ignore it.
    – jolyonruss
    Nov 12, 2015 at 14:26
  • 4
    @jolyonruss: Yep, JSX / ReactDOM works with the DOM API, not HTML. Nov 12, 2015 at 15:11
6

You could use null

<button type='button' disabled={this.state.submitting ? 'disabled' : null} onClick={this.handleSubmit}>Submit</button>
3

If you wanted the disabled attr to be added dependant on some condition you can do something like this:

const disableBtnProps = {};
if (some condition) {
  disableBtnProps.disabled = false;
} else {
 disableBtnProps.disabled = true;
}

Then in your component you could do:

 <Button {...disableBtnProps} className="btn"> my button </Button>
2

If you are using typescript you can add optional property in your type/interface of your Button component

disabled?: boolean

Making disabled an optional property we are allowing boolean and undefined

So if a boolean value of disabled is passed as a prop it will add the disabled attribute to the button with the value passed. If disabled prop is not passed in that case its value is considered as an undefined and the disabled attribute will not be added.

import { ReactNode } from 'react'

type Props = {
  disabled?: boolean
  type: 'button' | 'reset' | 'submit'
  btnClass: string
  children: ReactNode
  onClick?: () => void
}

function Button({
  type,
  disabled,
  btnClass,
  children,
  onClick,
}: Props): JSX.Element {
  return (
    <button
      onClick={onClick}
      type={type}
      disabled={disabled}
      className={btnClass}
    >
      {children}
    </button>
  )
}

export default Button

This will avoid any necessary checks and make the code more strictly checked

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.