Last updated: Apr 7, 2024
Reading time·2 min
To check if an input is empty in React:
trim()
method on the field's value.length
property on the value.0
, then it is empty, otherwise it
isn't.import {useState} from 'react'; export default function App() { const [message, setMessage] = useState(''); const handleChange = event => { setMessage(event.target.value); }; const handleClick = event => { event.preventDefault(); if (message.trim().length !== 0) { console.log('input value is NOT empty'); } else { console.log('input value is empty'); } }; return ( <div> <h2>String: {message}</h2> <input id="message" name="message" onChange={handleChange} autoComplete="off" /> <br /> <br /> <button onClick={handleClick}>Check if input empty</button> </div> ); }
We used the trim() method to remove any leading or trailing whitespace from the field's value.
console.dir(' bobbyhadz.com '.trim()); // 👉️ "bobbyhadz.com" console.dir(' '.trim()); // 👉️ ""
This helps us make sure that the user cannot just enter an empty space to get around our validation.
If the length
of the field's value is not equal to 0
after calling the
trim()
method on it, then the field contains at least 1
character.
If your use case requires more than 1
character for the input to not be
considered empty, adjust your if
statement.
const str = 'hello'; if (str.trim().length > 2) { console.log('String contains more than 2 characters'); }
The if
block would only run if the str
variable stores a string that
contains at least 3
characters.
We set the onClick
prop on the button element, so every time the button is
clicked, the handleClick
function is invoked.
const handleClick = event => { event.preventDefault(); if (message.trim().length !== 0) { console.log('input value is NOT empty'); } else { console.log('input value is empty'); } };
If you need to turn off autocomplete on an input field, check out the following article.
However, you can also check if an input field's value is empty directly in the
handleChange
function.
import {useState} from 'react'; export default function App() { const [message, setMessage] = useState(''); const handleChange = event => { setMessage(event.target.value); if (event.target.value.trim().length > 0) { console.log('✅ Input is not empty'); } else { console.log('⛔️ Input is empty'); } }; return ( <div> <h2>String: {message}</h2> <input id="message" name="message" onChange={handleChange} autoComplete="off" /> <button disabled={message.length === 0}>Click</button> </div> ); }
We set the onChange
prop on the input
element, so every time its value
changes, the handleChange
function gets invoked.
We used the same approach to check if the input field is empty.
Notice that we also determine if a button is disabled or not based on the length of the input field's value.
If the input is empty, the button is disabled, otherwise, it isn't.