tesicg
tesicg

Reputation: 4053

How to check object in React for null or empty or undefined?

I have the following sequence of code in React:

{financialPerformance && (
  financialPerformance.isConfirmed ? (
    <L.Text txtGray>Confirmed</L.Text>
  ) : (
    <L.Text txtGray>Not Confirmed</L.Text>
  )
)}

I have to check financialPerformance itself as well for null or empty or undefined and display "Non Confirmed" message. I mean on first appearance of financialPerformance object.

{financialPerformance && (

How can I do that inside or out of block above?

Upvotes: 3

Views: 31033

Answers (2)

phaybein
phaybein

Reputation: 1

You could be explicit and do the following...

// Check specifically for null or undefined
if(financialPerformance === null || financialPerformance === undefined) {
            // Code...
}

// Checking for zero, could be returned ( not sure on your data )
if(financialPerformance === 0 || financialPerformance) {
             // Code...
}

Upvotes: -1

falinsky
falinsky

Reputation: 7428

Due to null and undefined will be evaluated to false in boolean context - you can just combine your checks at one place:

{
  financialPerformance && financialPerformance.isConfirmed ? (
    <L.Text txtGray>Confirmed</L.Text>
  ) : (
    <L.Text txtGray>Not Confirmed</L.Text>
  )
}

Upvotes: 15

Related Questions