Check if a String is Empty in React

avatar

Borislav Hadzhiev

Mon Apr 25 20222 min read

banner

Photo by Max

Check if a String is Empty in React #

To check if a string is empty in React, access its length property and check if it's equal to 0, e.g. if (str.length === 0) {}. If the string's length is equal to 0, then the string is empty, otherwise it isn't empty.

App.js
import {useEffect, useState} from 'react'; export default function App() { const [message, setMessage] = useState(''); useEffect(() => { if (typeof message === 'string' && message.length === 0) { console.log('string is empty'); } else { console.log('string is NOT empty'); } // 👇️ trim leading and trailing whitespace if (typeof message === 'string' && message.trim().length === 0) { console.log('string is empty'); } else { console.log('string is NOT empty'); } }, [message]); return ( <div> <h2>String: {message}</h2> <button onClick={() => setMessage('Hello world')}>Set state</button> </div> ); }

check if string is empty

The first if statement checks if the message variable stores a value of type string and the string is empty.

If you consider an empty string one that contains only spaces, you can use the trim() method to remove any leading or trailing whitespace before checking if the string is empty.

App.js
const str = ' '; if (typeof str === 'string' && str.trim().length === 0) { console.log('string is empty'); } else { console.log('string is NOT empty'); }

The trim() method removes the leading and trailing spaces from a string. If the string contains only spaces, trim() returns an empty string.

To check if a string is truthy and contains one or more characters, add the string to an if statement.

App.js
const str = 'hello world'; if (str) { // if this code block runs // 👉️ str is NOT "", undefined, null, 0, false, NaN console.log('string is truthy'); }

The code in the if block wouldn't run if the str variable is set to an empty string, undefined, null, 0, false or NaN.

To be explicit, you can check if the string is equal to an empty string.

App.js
const str = ''; if (typeof str === 'string' && str !== '') { // if this code block runs // 👉️ string is NOT empty }

The if statement checks whether the str variable stores a value of type string and its value is not equal to an empty string.

This approach wouldn't work for a string that contains an empty space " ". In that scenario, we have to trim the space before checking if the string is empty.

App.js
const str = ' '; if (typeof str === 'string' && str.trim() !== '') { // if this code block runs // 👉️ string is NOT empty }

The trim() method removes leading and trailing whitespace, so the if block would run only if the str variable contains at least 1 character.

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