Search code examples
javascriptreactjsconditional-operator

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


Solution

  • <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
    </>