Check if an Input is Empty in React


Borislav Hadzhiev

Last updated: Apr 25, 2022


Photo from Unsplash

Check if an Input is Empty in React #

To check if an input is empty in React:

  1. Call the trim() method on the field's value.
  2. Access the length property on the value.
  3. If the field's value has a length of 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(; }; 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> ); }

check if input value is empty

We used the trim() method to remove any leading or trailing whitespace from the field's value.

console.log(' hi '.trim()); // 👉️ "hi" console.log(' '.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 characters 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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.