Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default disabled button click event is not firing on reactjs

Tags:

I have button which by default was disabled. But when the checkbox was selected, button will be enabled, using ref i am enabling the button. After the button activated click event is not firing. Without the default disable, button's click event was firing.

    class TodoApp extends React.Component {

        onChangeCheckBox(event) {
            if(event.target.checked) {
                this.actionButtonRef.disabled = "";
            }
            else {
                this.actionButtonRef.disabled = "disabled";

            }
        }  

        render() {
            return (
            <div>
                <input 
                    type="checkbox" 
                    ref={element => {
                        this.checkboxAllRef = element;
                    }}
                    onChange={event => this.onChangeCheckBox(event)}/> Checbox 
                <br />
                <button
                    type="button"
                    className="btn btn-danger" 
                    ref={element => {
                        this.actionButtonRef = element;
                    }}
                    onClick={event => {
                        alert("clicked");
                    }} 
                    disabled="disabled">Button</button>
            </div>
            )
        }
    }

    ReactDOM.render(<TodoApp />, document.querySelector("#app"))

here is jsfiddle

like image 397
Sivabalan Avatar asked Apr 25 '18 14:04

Sivabalan


1 Answers

Manual mutation of DOM elements (actually say virtual DOM) is not allowed by React.

You need to keep the enabled or disabled state. And work based on the state changes:

Class Constructor:

  constructor(props) {
    super(props);

    this.state = {
      checked: false
    };

    this.onChangeCheckBox = this.onChangeCheckBox.bind(this);
    this.onClickButton = this.onClickButton.bind(this);
  }

Event Handlers:

  onChangeCheckBox(e) {
    this.setState({
      checked: e.target.checked,
    });
  }
  onClickButton(e) {
    alert(e);
  }

Render JSX:

  render() {
    return (
      <div>
        <input
          type="checkbox"
          checked={this.state.checked}
          onChange={this.onChangeCheckBox}
        />
        <button
          type="button"
          disabled={!this.state.checked}
          onClick={this.onClickButton}>Click</button>
      </div>
    );
  }
}

Here is a demo.

like image 193
Bhojendra Rauniyar Avatar answered Oct 12 '22 07:10

Bhojendra Rauniyar