Warre Buysse
Warre Buysse

Reputation: 1345

(React) If-else statement in foreach loop in JSX

So I have the following:

// Build the component HTML.
return (
  <dl className={ classes }>

    {items.map((item, index) =>
      { item.type === 'dd' ?
        <dd key={ index } index={ index }>{ item.text }</dd>
        :
        <dt className="search-result__description-list__description" key={ index } index={ index }>{ item.text }</dt>
      }
    )}

  </dl>
);

The problem: nothing is rendering. The data is present in items. When I simply log the content without the if-else statement it also returns my data. However, when I use the if-else statement nothing shows up. No errors ether.

Any thoughts?

Upvotes: 0

Views: 5041

Answers (2)

Everettss
Everettss

Reputation: 16069

You forgot return statement

// Build the component HTML.
return (
  <dl className={ classes }>

    {items.map((item, index) =>
      { return item.type === 'dd' ?
        <dd key={ index } index={ index }>{ item.text }</dd>
        :
        <dt className="search-result__description-list__description" key={ index } index={ index }>{ item.text }</dt>
      }
    )}

  </dl>
);

You can see this fiddle with the same logic: https://jsfiddle.net/69z2wepo/94452/

Upvotes: 5

slugo
slugo

Reputation: 1039

The problem is in your arrow function, when using the block syntax ({}s following the arrow), you will need to specify the returned value using the return keyword.

Upvotes: 1

Related Questions