Hi Friends 👋,

Welcome To Infinitbility! ❤️

To check or handle undefined in react js, use the if statement it will go inside in if statement if the value is not undefined.

Basically, If the statement will handle all your false values like 0, false, "", undefined, etc.

let value = undefined;

  console.log("value have some data")
} else {
  console.log("value is undefined")

Today, I’m going to show you How do I check or handle undefined in react js, as above mentioned, I’m going to use the if statement to check value is undefined or has some data.

Let’s start today’s tutorial how do you check or handle undefined in react js?

React js check undefined example

Here, we will take the example of two states one state has some data and another has an undefined value, we will check both state console the undefined state name.

import React, { useState, useEffect } from "react";
export default function App() {
  const [str1] = useState("Infinitbility");
  const [str2] = useState(undefined);

  useEffect(() => {
    if (str1) {
      console.log("str1 have data");
    } else {
      console.log("str1 is undefined");

    if (str2) {
      console.log("str2 have data");
    } else {
      console.log("str2 is undefined");
  }, []);

  return (
    <div className="App">
      <p>{str1 ? "str1 have data" : "str1 is undefined"}</p>
      <p>{str2 ? "str2 have data" : "str2 is undefined"}</p>

In the above example, I have also put the example check undefined in render code here to check undefined we can use the ternary operator.

I hope it helps you, All the best 👍.