Categories
React Answers

How to Disable Button with React?

Spread the love

Sometimes, we want to disable buttons in our React components.

In this article, we’ll look at how to disable buttons in our React components.

Disable Button with React

We can disable a button with React by setting the disabled prop of the button.

For instance, we can write:

<button disabled={!this.state.value} />

We can use it in a component by writing:

class ItemForm extends React.Component {
  constructor() {
    super();
    this.state = { value: '' };
    this.onChange = this.onChange.bind(this);
    this.add = this.add.bind(this);
  }

  add() {
    this.props.addItem(this.state.value);
    this.setState({ value: '' });
  }

  onChange(e) {
    this.setState({ value: e.target.value });
  }

  render() {
    return (
      <div>
        <input
          type="text"
          value={this.state.value}
          onChange={this.onChange}
          placeholder='item name'
        />
        <button
          disabled={!this.state.value}
          onClick={this.add}
        >
          Add
        </button>
      </div>
    );
  }

We pass in the value state to let us enter the data that we want into the input field.

Then we check that in disabled prop of the button.

This way, the button is disabled if we have nothing inputted into the form field.

Conclusion

We can disable a button with React by setting the disabled prop of the button.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *