Best way to handle null values in ReactJS?

Asked
Active3 hr before
Viewed126 times

9 Answers

handle
90%

It looks like you're trying to access the property items of a variable x.,And if x is undefined, then calling x.items will give you the error you mentioned., By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Doing a simple:

if (x) {
   // CODE here
}

or

if (x && x.items) { // ensures both x and x.items are not undefined
   // CODE here
}

You can now use Optional Chaining, which looks sweet:

if (x?.items)
load more v
88%

One aspect of JavaScript development that many developers struggle with is dealing with optional values. What are the best strategies to minimize errors caused by values that could be null, undefined, or otherwise uninitialized at runtime?,JavaScript, software leadership, software development, and related technologies.,In your own functions, you can avoid creating null or undefined values to begin with. There are a couple ways to do that built into JavaScript that spring to mind. See below.

Pretag
 Pretag team - issue, fix, solve, resolve
72%

In our case, even though null is falsey, it's still a value!,Your app will crash because it doesn't know how to handle that:,Inside our App component, if dates ends up being falsey, it will be initialized with null.

const SomeComponent = ({ items = [], todaysDate, tomorrowsDate }) => {
  const [someState, setSomeState] = useState(null)

  return (
    <div>
      <h2>Today is {todaysDate}</h2>
      <small>And tomorrow is {tomorrowsDate}</small>
      <hr />
      {items.map((item, index) => (
        <span key={`item_${index}`}>{item.email}</span>
      ))}
    </div>
  )
}

const App = ({ dates, ...otherProps }) => {
  let items
  if (dates) {
    items = dates ? dates.map((d) => new Date(d).toLocaleDateString()) : null
  }

  return (
    <div>
      <SomeComponent {...otherProps} items={items} />
    </div>
  )
}
load more v
65%

This example renders a different greeting depending on the value of isLoggedIn prop.,Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like if or the conditional operator to create elements representing the current state, and let React update the UI to match them.,Another method for conditionally rendering elements inline is to use the JavaScript conditional operator condition ? true : false.

function UserGreeting(props) {
  return <h1>Welcome back!</h1>;
}

function GuestGreeting(props) {
  return <h1>Please sign up.</h1>;
}
load more v
75%

Pretag
 Pretag team - issue, fix, solve, resolve
40%

@ericvaladas Your sandbox examples appear to be using refs and not controlled components.,My takeaway so far is that changing the semantics of null as suggested in some comments in this thread will not reduce the confusion.,Per issue referenced above, the React team has planned on treating null as an empty string, but that hasn't yet occurred. I'd like to propose tackling this problem in the near future.

const someObject = {
   a: null,
};

someObject.a; // existent property, defined as null
someObject.b; // inexistent property, returns undefined

/* versus */

const someObject = {
   a: undefined,
};

someObject.a; // existent property, defined as undefined
someObject.b; // inexistent property, but returns undefined as above
load more v
22%

null, but also undefined, represent in JavaScript empty values. So what’s the exact difference between them?,Is it good that JavaScript has both undefined and null to represent empty values?,Implicitly, without return statement, a JavaScript function returns undefined.

let company;
company; // => undefined
let person = {
   name: 'John Smith'
};
person.age; // => undefined
load more v
60%

I am trying to pass the value of fileId as N if sessionStorage.getItem('uploadedFiles') is null. However, if the value exists, I want to pass the existing value from the session storage.,What I am trying to achieve:,User uploads a file using the Attach Files button. So inside fileUpload function, I am storing the value of fileId in session storage using the following code:


     growlComp.show({
        severity: 'success',
        summary: 'File Upload successful',
        detail: 'File Upload was successful'
     })
     sessionStorage.setItem('uploadedFiles', JSON.stringify(fileArray))
load more v
48%

Generally, it is a good idea to catch both null and undefined values, as both represent an absence of a value.,That means checking for null cannt be performed using typeof.,Finally, to check if a value has been declared and assigned a value that is neither null nor undefined, use typeof:

Pretag
 Pretag team - issue, fix, solve, resolve

Other "handle-undefined" queries related to "Best way to handle null values in ReactJS?"