Umair Jameel
Umair Jameel

Reputation: 1673

How to render conditional HTML elements in React

What is wrong with the following code? I have tried many options given in the link.

  { 
      !hideCurrentLocation && (
        {currentLocation?.city}
        {currentLocation?.city && ', '}
        {currentLocation?.country_code2}
      )
  }

It is giving error on line {currentLocation?.city} that a comma is required.

Upvotes: 2

Views: 47

Answers (1)

Drew Reese
Drew Reese

Reputation: 202608

Too many brackets. Also, if you're trying to render a "city, countrycode" you need to return a single node for valid JSX. I suggest dumping the city and country code into an array and joining them into a single string.

{!hideCurrentLocation && (
  <>
    {[currentLocation?.city, currentLocation?.country_code2]
      .filter(Boolean)
      .join(", ")}
  </>
)}

Upvotes: 2

Related Questions