by Sai gowtham

How to disable a button in React

Learn, how to disable or enable a button in React.

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 by passing a boolean value to the disabled attribute.

Example:

App.js
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.

App.js
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;

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course