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>

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 less time.
Learn MoreRecommended

How to Save Writable Store in Svelte to Local Storage
Learn how to create a persistent store in Svelte

How to Create an Infinite Scroll Component in React
With the help of the Intersection Observer API
