There are a few ways in react that you can disable a button. Let us look at some of the ways.
Option 1. When input value is empty
- Set the input value in the prop
- Once the input field has a value the button is enabled
Here is an example below:
class Data extends Component {
constructor(props) {
super(props);
this.state = {
amount:"",
};
}
render() {
return (
<div className="container">
<div className="col-6 mx-auto">
<form>
<div className="mb-3">
<input type="text" className="form-control" value={this.state.amount} onChange={e => this.setState({amount:e.target.value})} required/>
</div>
<button className="btn btn-primary" disabled={!this.state.amount}>Enter</button>
</form>
</div>
</div>
)
}
}
export default Data;
Option 2. Place value directly in disable prop
<button className="btn btn-primary" disabled={true}>Enter</button>
Option 3. Use a conditional statement
- Set a state to the disable prop
- Button will enable or disable based on value of state
class Data extends Component {
constructor(props) {
super(props);
this.state = {
amount:"",
onSubmit:false
};
this.handleSubmit = this.handleSubmit.bind(this)
}
handleSubmit (e) {
e.preventDefault();
this.setState({onSubmit:!this.state.onSubmit}); //button turns false on submit
}
render() {
return (
<div className="container">
<div className="col-6 mx-auto">
<form onSubmit={this.handleSubmit}>
<div className="mb-3">
<input type="text" className="form-control" value={this.state.amount} onChange={e => this.setState({amount:e.target.value})} required/>
</div>
<button className="btn btn-primary" disabled={this.state.onSubmit}>Enter</button>
</form>
</div>
</div>
)
}
}
export default Data;