user11657234
user11657234

Reputation:

Using a ternary operator to control whether or not to map over state

I want to use a ternary operator to control whether or not you map over allTestTypes. allTestTypes is supposed to be used to populate the options parameter in DropdownSingle

{allTestTypes.map(item => item.test_type )}
  {!level ? null :
    <React.Fragment>
      <div>{configs[level].name}:</div>
      <DropdownSingle 
        name={configs[level].name} 
        value={testType} 
        options={configs[level].dropdownValues} 
        onChange={onTestFieldUpdate}
      />
    </React.Fragment>
  })

Update:

{!level ? setAllTestTypes.map((item => null :
            <React.Fragment>
              <div>{configs[level].name}:</div>
              <DropdownSingle 
                name={configs[level].name} 
                value={testType} 
                options={configs[level].dropdownValues} 
                onChange={onTestFieldUpdate}
              />
            </React.Fragment>
          )
        })

Error:

enter image description here

update 2:

{!level ? null : setAllTestTypes.map((item) =>
            <React.Fragment>
              <div>{configs[level].name}:</div>
              <DropdownSingle 
                name={configs[level].name} 
                value={testType} 
                options={item.test_type} 
                onChange={onTestFieldUpdate}
              />
            </React.Fragment>
          
          )})

Error 2: enter image description here

Response: enter image description here

Sazzad updated error: enter image description here

Upvotes: 0

Views: 291

Answers (4)

sazzad
sazzad

Reputation: 525

you are missing a closing } . this should fix it.

{!level ? setAllTestTypes.map((item =>
        <React.Fragment>
          <div>{configs[level].name}:</div>
          <DropdownSingle 
            name={configs[level].name} 
            value={testType} 
            options={configs[level].dropdownValues} 
            onChange={onTestFieldUpdate}
          />
        </React.Fragment>
      )
    }) : null
}

Upvotes: 0

Joe Seifi
Joe Seifi

Reputation: 1725

const foo = truthy ? <jsx /> : null - or - const foo = truthy && <jsx />

Upvotes: 0

Sapinder Singh
Sapinder Singh

Reputation: 351

condition ? functionForMapping : oppositeCase

You may either place the entire mapping statement here, or just simply wrap it in another function.

Upvotes: 0

Jacob Smit
Jacob Smit

Reputation: 2379

If you want to check a condition before mapping any array items:

<div>
    {
        !!condition && (
            array.map(item => item /* Mapping Function */)
        )
    }
</div>

If you wish to only map certain items use filter:

<div>
    {
        array
            .filter(item => !!item /* Condition */)
            .map(item => item /* Mapping Function */)
    }
</div>

Upvotes: 0

Related Questions