Disable does not work for checkbox when using this.props

13,680

When using react, disabled it's a prop that you need to set true or false. When you just define the prop without a value, and this prop it's boolean, then by default sets the value to true. That's why it works when you manually define the prop.

<input type="checkbox" disabled={false} />
<input type="checkbox" disabled={true} />
<input type="checkbox" disabled />
<input type="checkbox" id={"delivery-" + this.props.ID} disabled={this.props.disableIt} />

For example:

var Example = React.createClass({
  getInitialState: function() {
    return {
      disabled: false
    };
  },

  toggle: function() {
    this.setState({
      disabled: !this.state.disabled
    });
  },

  render: function() {
    return (
      <div>
        <p>Click the button to enable/disable the checkbox!</p>
        <p><input type="button" value="Enable/Disable" onClick={this.toggle} /></p>
        <label>
          <input type="checkbox" disabled={this.state.disabled} />
          I like bananas!
        </label>
      </div>
    );
  }
});

ReactDOM.render(
  <Example />,
  document.getElementById('container')
);

Here's the working example: https://jsfiddle.net/crysfel/69z2wepo/59502/

Good luck!

Share:
13,680
g_b
Author by

g_b

Updated on June 17, 2022

Comments

  • g_b
    g_b almost 2 years

    How do I make this work?

    <input type="checkbox" id={"delivery-" + this.props.ID} {this.props.disableIt ? 'disabled' : ''} />
    

    I was expecting this code - {this.props.disableIt ? 'disabled' : ''} - to output a 'disabled' attribute, but it throws 'Unexpected token (102:89)'. But if I directly just put a static 'disabled' word in there, it works.