Author -  Sai gowtham

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:

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;

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY