Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSX: Conditional statement within a map

I'm trying to understand how to incorporate conditional statements within JSX. I have an array of objects that I'm mapping to a select box. I want to exclude items that include the substring "threshold" in indicator.name.

So I can't use a ternary operator, because there's no "or" item. But I can't figure out how to include an if statement within this map. Whatever I try I get an error.

<select
  defaultValue={defaultValue}
  onChange={e => setIndicator(e.currentTarget.value)}
  disabled={loading}
>
  <option key='' value=''>
    Select
  </option>
  {indicatorList.map(indicator => (
    <option key={indicator.name} value={indicator.name}>
      {indicator.label}
    </option>
  ))}
</select>
like image 703
Cineno28 Avatar asked Jan 02 '26 02:01

Cineno28


1 Answers

you can filter then map:

<select
  defaultValue={defaultValue}
  onChange={e => setIndicator(e.currentTarget.value)}
  disabled={loading}
>
  <option key='' value=''>
    Select
  </option>
  {indicatorList.filter(indicator=>indicator.name.includes('threshold')).map(indicator => (
    <option key={indicator.name} value={indicator.name}>
      {indicator.label}
    </option>
  ))}
</select>

Or return null:

<select
  defaultValue={defaultValue}
  onChange={e => setIndicator(e.currentTarget.value)}
  disabled={loading}
>
  <option key='' value=''>
    Select
  </option>
  {indicatorList.map(indicator => (
    indicator.name.includes('threshold')?<option key={indicator.name} value={indicator.name}>:nul
      {indicator.label}
    </option>
  ))}
</select>
like image 130
Nilanka Manoj Avatar answered Jan 03 '26 15:01

Nilanka Manoj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!