How to Disable a Button when an Input field is Empty in React

#react

Last updated on Sep 16, 2020 by Suraj Sharma



In this tutorial, you will learn how you can disable a button element when an input field is empty.



Getting started


Suppose, we have a Form Component with one <input /> text field and a <button /> element.


import React from 'react';

const Form = () => {
  return (
    <form>
      <input type="text" value="" />
      <button>Submit</button> 
    </form>
  )
}

export default Form;


Initially when the component is rendered, the button should be disabled for the empty input field.


The input field value is stored in the Form's local state value, which gets updated via an onChange event handler handleChange as soon as a user starts typing on the input field.


const Form = () => {
  const [value, setValue] = React.useState('');

  const handleChange = (event) => {
    setValue(event.target.value);
  };

  return (
    <form>
      <input type="text" value={value} onChange={handleChange}/>
      <button>Submit</button> 
    </form>
  )
}


The handleChange calls the setValue to change the state value



Disabling the Button


To disable the button, we are going to use disabled attribute of the button.

When the input field is empty, disabled attribute should be true and when a user types a first character, disabled is changed to false.

That means, disabled should be equal to !value. So our final <button /> element should look like:


return (
  <form>
    <input type="text" value={value} onChange={handleChange}/>
    <button disabled={!value}>Submit</button> 
  </form>
)


Related Articles




Suraj Sharma is a JavaScript Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.