gpbaculio
gpbaculio

Reputation: 5968

How to check if button in react is disabled?

I have this code for my button that doesn't work, FOR the title:

<Button 
        id="completeSelectedButton"
        title={Boolean(document.getElementById('completeSelectedButton').disabled) ? 'Some of the selected todos is already Complete.' : '' }
        disabled={Boolean((this.state.checkedIds.length !== 0) && // check if not empty
                           this.state.checkedIds.length === todos.filter(({id, completed}) => this.state.checkedIds.includes(id) && completed === false ).length) ? false : true // if it matched, ALL THE CHECKED TODOS ARE UNFINISHED OR HAS completed property === false
                  } 
        onClick={() => {
          onCompleteMultipleClick(this.state.checkedIds)
          this.setState({checkedIds:[]});
        }} 
      >

I want to set the title if the button is disabled, but I think it's not working because I am having this error, I think React cannot find it?

Uncaught TypeError: Cannot read property 'disabled' of null

Upvotes: 2

Views: 5367

Answers (1)

Ross Allen
Ross Allen

Reputation: 44880

You should rarely need to read from the DOM in React components. The DOM is a reflection of the props and state of your components, so you already know everything that the DOM might tell you. In this case, extract the value to a variable and reference it in both places:

const disabled = Boolean(
    (this.state.checkedIds.length !== 0) && // check if not empty
    this.state.checkedIds.length === todos.filter(({id, completed}) => this.state.checkedIds.includes(id) && completed === false ).length
  ) ?
  false :
  true // if it matched, ALL THE CHECKED TODOS ARE UNFINISHED OR HAS completed property === false

<Button 
  id="completeSelectedButton"
  title={disabled ? 'Some of the selected todos is already Complete.' : '' }
  disabled={disabled} 
  onClick={() => {
    onCompleteMultipleClick(this.state.checkedIds)
    this.setState({checkedIds:[]});
  }} 
>

Upvotes: 1

Related Questions