简体   繁体   中英

How do I use null within a ternary expression?

I am rendering a page with react and react-bootstrap, with the use of <ListGroup> and <ListGroupItem> . The following is my code, and I'm trying to use bsStyle='info' when the status is not '1' , and leave it blank when status is '1' .

<ListGroup>
  {tables.map(table => (
    <ListGroupItem
      key={`table.${table.id}`}
      header=(table.name)
      bsStyle={table.status !== '1' ? ('info') : ('')}
      >
      {table.content} - 
    </ListGroupItem>
  ))}
</ListGroup>

It rendered properly but keeps getting the following warning due to validation of bsStyle:

Warning: Failed prop type: Invalid prop `bsStyle` of value `` supplied to `ListGroupItem`, expected one of ["success","warning","danger","info"].

There is a workaround to escape the validation by setting bsStyle={null} . However I can't get it works within the ternary expression. The following code will make it a string bsStyle='{null}' .

<ListGroup>
  {tables.map(table => (
    <ListGroupItem
      key={`table.${table.id}`}
      header=(table.name)
      bsStyle={table.status !== '1' ? ('info') : ('{null}')}
      >
      {table.content} - 
    </ListGroupItem>
  ))}
</ListGroup>

What is the proper way to pass {null} without making it a string?

EDITED: Supposed to be '{null}' and not '{null' up there.

Your ternary operator's second operand is off:

('{null}')

That evaluates to literally "{null}" . Try this:

bsStyle={table.status !== '1' ? 'info' : null}

Just use null plainly, do not wrap it in quotes. Here's a JSFiddle example .

You probably want to ommit whole bsStyle attribute in case status is not different from 1

<ListGroupItem
   key={`table.${table.id}`}
   header=(table.name)
   {...( table.status !== '1' ? {bsStyle:'info'} : {} )}
  >

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM