Categories
React Answers

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

Spread the love

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.

By John Au-Yeung

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

One reply on “How to disable a button when an input is empty with React?”

Leave a Reply

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