Check if an Input is Empty in React

avatar

Borislav Hadzhiev

Mon Apr 25 20221 min read

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.
App.js
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> ); }

check if input value is empty

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

App.js
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.

App.js
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.

Use the search field on my Home Page to filter through my more than 1,000 articles.