Disabling Buttons in React Based on Input Fields

Ferenc Almasi • 2022 September 08 • 📖 2 min read

To disable buttons in React based on the value of an input field, use the disabled prop with a value pointing to a useState hook:

import { useState } from 'react'

export default function App() {
    const [email, setEmail] = useState('')

    return (
        <div>
            <input
                type="email"
                value={email}
                onChange={event => setEmail(event.target.value)}
            />

            <button disabled={!email}>Subscribe</button>
        </div>
    )
}
Enable button when the input field is filled
Copied to clipboard!

In this code example, we only want to enable the button once the email input field has some value. We can achieve this by introducing a new useState hook, and set the value of the input field to this variable using an onChange event.

This negated value is then used for the disabled prop, telling React to only enable the button if the field is not empty. Note that empty strings are evaluated as false in JavaScript.

You can do the same with multiple input fields too, you just need to combine the different useState variables together for the disabled prop.

Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
JavaScript Course

Disable button after clicking it

You could also disable buttons after clicking them to prevent multiple clicks by attaching an onClick event listener to the button and set the currentTarget.disabled property to true:

const disableOnClick = event => event.currentTarget.disabled = true

return <button onClick={disableOnClick}>Send</button>
Allow buttons only to be clicked once
Copied to clipboard!
JavaScript Course Dashboard

Tired of looking for tutorials?

You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.

Check out our interactive course to master JavaScript in 5 hours.

Learn More

📚 Get access to exclusive content

Want to get access to exclusive content? Support webtips with the price of a coffee to get access to tips, checklists, cheatsheets, and much more. ☕

Get access Support us
Read more on
🎉 Thank you for subscribing to our newsletter. x