JorgeeFG
JorgeeFG

Reputation: 5961

Why this React return code is invalid? (Conditional rendering)

I want to understand why the compiled version of this code is invalid

<Fragment>
  {listData.list.description && (
    <div>
      <div dangerouslySetInnerHTML={{ __html: list.description }} />
      {hasTopCollection && <ImageAttribution />}
    </div> 
       // ^ ) expected
    {list.listOptions.brandHeaderType === 20 && <SomeComponent />}
 // ^ Parsing error: Unexpected token, expected ","
  )}
</Fragment>

I had this listData.list.description && <Description> component in a parent component, but now I want to move this logic into the actual <Description> component.

So before this was like this:

<Fragment>
    <div>
      <div dangerouslySetInnerHTML={{ __html: list.description }} />
      {hasTopCollection && <ImageAttribution />}
    </div>
    {list.listOptions.brandHeaderType === 20 && <SomeComponent />}
</Fragment>

Upvotes: 0

Views: 34

Answers (1)

David
David

Reputation: 218867

The <Fragment> now only has one child, so it isn't really needed. However, inside the parentheses you have two things. And parentheses alone aren't sufficient to group children, so a <Fragment> can be used there in their place:

{listData.list.description &&
  <Fragment>
    <div>
      <div dangerouslySetInnerHTML={{ __html: list.description }} />
      {hasTopCollection && <ImageAttribution />}
    </div> 
    {list.listOptions.brandHeaderType === 20 && <SomeComponent />}
  </Fragment>}

Upvotes: 1

Related Questions