Last updated: Apr 7, 2024
Reading timeยท4 min
If you need to check if a string is empty in React, click on the second subheading.
To check if an array is empty in React, access its length
property, e.g.
arr.length
. If an array's length is equal to 0
, then it is empty.
If the array's length is greater than 0
, it isn't empty.
import {useEffect, useState} from 'react'; export default function App() { const [messages, setMessages] = useState([]); useEffect(() => { if (messages.length > 0) { console.log('array is NOT empty'); } if (messages?.length > 0) { console.log('array is NOT empty'); } if (messages.length === 0) { console.log('array is empty'); } }, [messages]); return ( <div> <h2>Array: {JSON.stringify(messages)}</h2> <button onClick={() => setMessages(current => [...current, 'hello'])}> Add message </button> </div> ); }
The first if
statement checks whether the array's
length
is greater than 0
.
if (messages.length > 0) { console.log('array is NOT empty'); }
The if
block will only run if the array isn't empty.
We set an onClick
prop on the button
element, so every time it's clicked a
function is invoked.
<button onClick={() => setMessages(current => [...current, 'hello'])}> Add message </button>
The function
adds an element to the state array each time
the button
is clicked.
Every time the state array changes, the useEffect
hook is run.
useEffect(() => { if (messages.length > 0) { console.log('array is NOT empty'); } if (messages?.length > 0) { console.log('array is NOT empty'); } if (messages.length === 0) { console.log('array is empty'); } }, [messages]);
In our useEffect
hook, we use the array's length to check if the array is
empty or not.
If the length of the array is equal to 0
, it's empty, otherwise, it contains
at least 1 element.
The second if
statement uses the
optional chaining (?.) operator to avoid
an error if the reference is nullish (null
or undefined
).
const arr = ['hi']; if (arr?.length > 0) { console.log('array is not empty'); }
The optional chaining (?.) operator short-circuits if the reference is nullish
(null
or undefined
).
In other words, if the arr
variable stores a null
or undefined
value, the
operator will return undefined
instead of trying to access the length
property on a null
value and cause a runtime error.
const arr = null; if (arr?.length > 0) { console.log('array is not empty'); }
If you need to check if an array is empty, check if its length
property
returns 0
.
const arr = []; if (arr.length === 0) { console.log('array is empty'); }
If you're unsure whether the variable stores an array, check for the type of its
value before accessing its length
property.
let arr = ['bobbyhadz.com']; if (Array.isArray(arr) && arr.length > 0) { // if this code block runs // ๐๏ธ arr is not empty console.log('arr is not empty') }
We have 2 conditions in the if
statement. We used the &&
(and) operator to
signify that both conditions have to be met for the if
block to run.
We first check if the arr
variable stores an array and then check if the
array's length is greater than 0
.
This approach is similar to the optional chaining one, but I prefer it because
the optional chaining approach doesn't account for the case when arr
is set to
a string
. Strings in JavaScript also have a length
property.
To check if a string is empty in React, access its length
property and check
if it's equal to 0
.
If the string's length is equal to 0
, then the string is empty, otherwise it
isn't empty.
import {useEffect, useState} from 'react'; export default function App() { const [message, setMessage] = useState(''); useEffect(() => { if (message.length === 0) { console.log('string is empty'); } else { console.log('string is NOT empty'); } // ๐๏ธ trim leading and trailing whitespace if (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> ); }
The first if
statement checks if the message
variable stores an empty
string.
if (message.length === 0) { console.log('string is empty'); } else { console.log('string is NOT empty'); }
We set the onClick
prop on the button element, so every time the button is
clicked, a function is invoked.
<button onClick={() => setMessage('Hello world')}> Set state </button>
On each click, we set the setMessage
state variable to a string and the
useEffect
hook runs.
trim()
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.
const str = ' '; if (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.
// ๐๏ธ "bobbyhadz.com" console.dir(' bobbyhadz.com ');
To check if a string is truthy and contains one or more characters, add the
string to an if
statement.
const str = 'bobbyhadz.com'; 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
.