g_b g_b - 1 month ago 23
React JSX Question

Disable does not work for checkbox when using this.props

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.

Answer

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!