John Rogerson
John Rogerson

Reputation: 1183

Ternary Operator in React/JSX Not Working

I'm mapping data from an eBay API pull, and trying to display an icon if the value equals true or nothing if false.

The field is called bestOfferEnabled and is either a value of 'true' or false.

This is example dataset https://pastebin.com/mqCscKss/

I'm trying this:

{item.listingInfo[0].bestOfferEnabled === true && (
            <i className="fas fa-comment-dollar"></i>
          )}

and it is not generating the icon. I've also tried various versions of this including true in quotes but nothing is working.

When i just try to output the text on the page doing this:

{item.listingInfo[0].bestOfferEnabled}

it does print out a true or false value

Upvotes: 2

Views: 295

Answers (1)

Jay Kariesch
Jay Kariesch

Reputation: 1482

This is because bestOfferEnabled is a key for an array:

listingInfo: [{
    bestOfferEnabled: [
        "false"
    ],
}]

So you'd have to do this:

{item.listingInfo[0].bestOfferEnabled[0] === true && (
            <i className="fas fa-comment-dollar"></i>
)}

You could also use the every Array method to ensure all values in the array are true:

{item.listingInfo[0].bestOfferEnabled.every(key => key) && (
            <i className="fas fa-comment-dollar"></i>
)}

More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

EDIT: As someone pointed out, your boolean values are strings, in which case you can use JSON.parse to convert them.

{item.listingInfo[0].bestOfferEnabled.every(key => JSON.parse(key)) && (
            <i className="fas fa-comment-dollar"></i>
)}

That should do the trick.

Upvotes: 2

Related Questions