Tim Bogdanov
Tim Bogdanov

Reputation: 240

JSX inside ternary not returning desired result

The problem:

I am trying to return an icon along with text if a ternary is true, and just text if ternary is false. Here is my code:

{quote.is_archived ? <PencilFill className="mr-10" size={ 10 }/>  + 'View' : 'Edit'}

When I do that, this is what I get, can someone point me to why this is happening.

enter image description here

Upvotes: 0

Views: 50

Answers (2)

Harsh Mehta
Harsh Mehta

Reputation: 131

Don't use + operator as it concats JSX with String.
Try ternary only at the place that you want to change like this.

<PencilFill className="mr-10" size={ 10 }/> 
{quote.is_archived ? 'View' : 'Edit'}

Upvotes: 1

Nicholas Tower
Nicholas Tower

Reputation: 84912

<PencilFill className="mr-10" size={ 10 }/> + 'View'

The first part of this is an object, and the second part is a string, so when you concatenate them together you get [object Object]View. What you probably meant to do was a Fragment, as in:

<React.Fragment>
  <PencilFill className="mr-10" size={ 10 }/>
  View
</React.Fragment>

Or using the shorthand notation:

<>
  <PencilFill className="mr-10" size={ 10 }/>
  View
</>

Upvotes: 5

Related Questions