[React] Conditional Rendering

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

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

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:

{false}
{null}
{undefined}
{true}

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

你可能感兴趣的:([React] Conditional Rendering)