bier hier
bier hier

Reputation: 22580

How to disable button based on state?

In my reactjs app I have a button that is disabled/enabled based on a state value:

<button disabled={this.state.modelvalue === 0 ? true : false} onClick={this.showMessage}>Select</button>

The modelvalue state is set by changing the select value:

<div className="row">
      <div className="col-md-6">
            <select name="" id="" value={this.state.modelvalue} onChange={this.handleChangeModel}>
              <option value ="0">plse select value</option>
              <option value ="1">One</option>
            </select>
      </div>
</div>

 handleChangeModel(event) {
    this.setState({modelvalue: event.target.value});
 }

The handleChangeModel sets the state.modelvalue but for some reason when you change from 'one' back to 'plse select value' the button does not get disabled? Even though the state.modelvalue is 0 again?

Upvotes: 1

Views: 7582

Answers (2)

Mayank Shukla
Mayank Shukla

Reputation: 104529

Because the selected value will be a string not a number, you need to write the condition like this:

disabled={this.state.modelvalue === '0'}   //string comparison 

Update:

As suggested by @RobG, instead of using === (check value with type) use == (check value without type) to check the value, it will work:

disabled={this.state.modelvalue == 0}

Upvotes: 2

Navneet Goel
Navneet Goel

Reputation: 174

Below is the correct code:

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      modelvalue: null
    }

    this.handleChangeModel = this.handleChangeModel.bind(this);
  }

 handleChangeModel(event) {
    this.setState({modelvalue: event.target.value});
 }


  render() {
    return (
      <div className="row">
      <div className="col-md-6">
            <select name="" id="" value={this.state.modelvalue} onChange={this.handleChangeModel}>
              <option value ="0">plse select value</option>
              <option value ="1">One</option>
            </select>
      </div>

      <button disabled={this.state.modelvalue === "0" ? true : false} onClick={this.showMessage}>Select</button>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

2 things that you missed: 1) Adding this.handleChangeModel = this.handleChangeModel.bind(this); in constructor so that you can bind context of this in handleChangeModel since its a callback method 2) Use this.state.modelvalue === "0" instead of this.state.modelvalue === 0

Upvotes: 1

Related Questions