Disabling Buttons in React Based on Input Fields
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>
)
}
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.

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>
Unlimited access to hundred of tutorials
Access to exclusive interactive lessons
Remove ads to learn without distractions