[React] Conditional Rendering

We always use the follow two ways to conditional render in JSX:

  • Ternary(Conditional) operator
render() {
    return (
      <div>  
        xxx
        <div>{ shouldShow ? 'Hey' : null }</div>
        xxx
      </div>
    );
  }
  • Logical conjunction
render() {
    return (
      <div>  
        xxx
        <div>{ shouldShow && 'Hey'}</div>
        xxx
      </div>
    );
  }

false, null, undefined, and true are valid children. They will be ignored( and skips the second expression), and simply don't render. These JSX expressions will all render to the same thing:

<div />

<div></div>

<div>{false}</div>

<div>{null}</div>

<div>{undefined}</div>

<div>{true}</div>

This JSX only renders the string Hey only when shouldShow is true:

And one thing special is that, when shouldShow is an integer 0:

For ternary operator, it will not render any thing.
For logical conjunction, it will rend an integer 0 there.

Actually, there are multiple ways to conditional show, if you are interesting with them, checkout them here.
if statement
ternary operation
logical && operator
switch case operator
enums
Multi-Level Conditional Rendering
With Higher Order Components
External Templating Components

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容