How to disable a button when an input is empty with React?

Sometimes, we want to disable a button when an input is empty with React.

In this article, we’ll look at how to disable a button when an input is empty with React.

How to disable a button when an input is empty with React?

To disable a button when an input is empty with React, we can set the input’s value as a state’s value.

Then we can use the state to conditionally disable the button when the state’s value is empty.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [name, setName] = useState();

  return (
    <div>
      <input onChange={(e) => setName(e.target.value)} />
      <button disabled={!name}>save</button>
    </div>
  );
}

to create the name state with the useState hook.

Then we add a text input element with its onChange prop set to a function that calls setName to set the input’s value as name‘s value.

e.target.value has the value of the input box.

Next, we add a button with the disabled prop set to !name to disable the button when the input box is empty.

Conclusion

To disable a button when an input is empty with React, we can set the input’s value as a state’s value.

Then we can use the state to conditionally disable the button when the state’s value is empty.