Home > Mobile >  JSX no work with nullish operator ? React
JSX no work with nullish operator ? React

Time:06-11

I want to show some element but no work ->

      { someArray.length > 0 ?? ( 
          <div>
            Test
          </div>  
        )}

but this is work ->

      {someArray.length > 0 ? (
        <> 
          <div>
              Test
          </div>
        </>
      ) : (
           <></>
      )}

Why my first block code no work?

CodePudding user response:

{ someArray.length > 0 && ( 
    <div>
       Test
    </div>  
)}

I hope this will help you. Thanks

CodePudding user response:

Nullish coalescing operator (??) returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

x > y will never be null, it will always be boolean.

Maybe you're looking for the Logical OR operator (||), or Logical AND operator (&&)?

{ someArray.length > 0 && ( 
    <div>
       Test
    </div>  
)}

But since you appear to want to only do something if there are elements in an array, why not just map the array?

{someArray.map(
  arrayElement => (
    <div>
      element {arrayElement}!
    </div>
  )
)}
  • Related