Yerlan Yeszhanov
Yerlan Yeszhanov

Reputation: 2449

How can I disable a button given a predicate

I don't know where I'm doing mistake , but it seems very odd . When I toggle ckeckbox I'm adding items in array and depending on that array I want my button to be disabled or not. If empty disable, else active. Items adds to array for sure . It does get active once when I add, but if I uncheck it , it does not get bisabled. What can be the problem?

activateButton() {
// arrayOfStatusId is an array 
if (this.state.arrayOfStatusId) { 
  this.setState({
    isButtonActive: false,
  })
} else{
   this.setState({
    isButtonActive: true,
  })
}
}


<Checkbox
  onClick={() => this.selectAllRespondents()}
  onChange={() => this.activateButton()}
/>

selectAllRespondents() {
    const { data, arrayOfStatusId, isCheckedAll } = this.state
    this.setState({
      isCheckedAll: !this.state.isCheckedAll,
    })
    if (!isCheckedAll) {
      for (let i = 0; i < data.length; i++) {
        arrayOfStatusId.push(data[i].status_id)
      }
    } else {
      this.setState({
        arrayOfStatusId: [],
      })
    }
  }

<Button disabled={isButtonActive}>
   ADD
</Button>

Upvotes: 0

Views: 96

Answers (3)

Maher
Maher

Reputation: 91

You need to check arrayOfStatusId length property

Upvotes: 0

Ashish
Ashish

Reputation: 4330

As per your code I think you should check for this.state.arrayOfStatusId && this.state.arrayOfStatusId.length. Becuse if arrayOfStatusId is an aray, it will always evaluate true, causing isButtonActive false always.

activateButton () => {
    // arrayOfStatusId is an array 
    if (this.state.arrayOfStatusId && this.state.arrayOfStatusId.length) { 
        this.setState({
            isButtonActive: false,
        })
    } else{
       this.setState({
           isButtonActive: true,
       })
    }
}


<Checkbox
  onClick={() => this.selectAllRespondents()}
  onChange={this.activateButton}
/>



<Button disabled={this.state.isButtonActive}>
    ADD
</Button>

Also, if you are using activateButton function to change value of this.state.isButtonActive and this value is used only as prop for Button you can remove the activateButton function also:

<Checkbox
  onClick={() => this.selectAllRespondents()}
/>

<Button disabled={this.state.arrayOfStatusId && this.state.arrayOfStatusId.length}>
    ADD
</Button>

Upvotes: 2

sathish kumar
sathish kumar

Reputation: 1507

your if statement is always true. bz this is array, you need to check array.length to test array is empty or not

state = {
 isButtonActive : false
}

activateButton() {
// arrayOfStatusId is an array 
if (this.state.arrayOfStatusId.length> 0) { 
  this.setState({
    isButtonActive:true,
  })
} else{
   this.setState({
    isButtonActive:false,
  })
}
}


<Checkbox
  onClick={() => this.selectAllRespondents()}
  onChange={() => this.activateButton()}
/>



<Button disabled={isButtonActive}>
   ADD
</Button>

Upvotes: 0

Related Questions