How to handle null values in React?

Sometimes, we want to handle null values in React.

In this article, we’ll look at how to handle null values in React.

How to handle null values in React?

To handle null values in React, we can use the optional chaining operator.

For instance, we write:

import React from "react";

const customer = {
  name: "Carl",
  details: {
    age: 22,
    location: "Paradise Falls"
  }
};

export default function App() {
  return <div>{customer.details?.address?.city}</div>;
}

We render the value of customer.details?.address?.city without crashing since we a used the optional chaining operator (?.) instead of the regular dot operator for accessing nested properties.

The optional chaining operator returns undefined when it tries to access a property that doesn’t exist or it’s set to null or undefined.

Conclusion

To handle null values in React, we can use the optional chaining operator.