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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With