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 React from start to finish.
Master React

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!
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Unlimited access to hundred of tutorials
  • check Access to exclusive interactive lessons
  • check Remove ads to learn without distractions
Become a Pro

Recommended