How to disable the button element in React
Learn, how to disable or enable a button element in React with the help of examples.
We mostly disabled the button when an input field or textarea value is empty in the search box, login/signup forms.
Disabling the button
We can disable the button in react by passing a boolean value to the disabled
attribute.
Here is an example:
import React, {useState} from "react";
function App() {
const [name, setName] = useState('');
const nameChange = e => setName(e.target.value);
return (
<div className="App">
<input value={name} onChange={nameChange} placeholder="Name"/>
<button disabled={!name}>Search</button> </div>
);
}
export default App;
In the above example, we are using the react hooks useState
hook to initialize the state.
The nameChange()
function is used to update the name
property with the user-entered data.
Inside the button
element we have passed disabled= {!name}
, so that the button is disabled when an input value is empty, otherwise button is enabled.
Similarly, in class components you can do it like this.
import React,{Component} from "react";
class App extends Component{
state = {
name: "" }
nameChange = e => {
this.setState({name:e.target.value});
};
render(){
return (
<div className="App">
<input value={this.state.name} onChange={this.nameChange}
placeholder="Name"/>
<button disabled={!this.state.name}>Search</button> </div>
);
}
}
export default App;