Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 445
g_b Avatar asked Oct 12 '16 03:10

g_b


1 Answers

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!

like image 133
Crysfel Avatar answered Sep 27 '22 17:09

Crysfel