[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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 11,552评论 0 23
  • 今天看到了引起我共鸣的片段,为之心动。即谈到人的战斗力和斗志。 在我看来战斗力和斗志要做一下粗略解释。 战斗力:顾...
    劦力阅读 213评论 0 2
  • 空山寂岭识归客,落日白云鸟依稀。 尽是旧景告人老,还知新年童子笑。
    应心阅读 198评论 0 0
  • 已经好久没有静下心来看书了总是有这样或者那样的事分散注意力。突然间就想起去年的这个时候,那个时候还在准备考研的事,...
    真真卒迹阅读 402评论 1 0

友情链接更多精彩内容