Skip to content

Latest commit

 

History

History
111 lines (95 loc) · 2.45 KB

18.conditionals-in-jsx.md

File metadata and controls

111 lines (95 loc) · 2.45 KB

Conditionals in JSX

Instead of

const sampleComponent = () => {
  return isTrue ? <p>True!</p> : null
};

Use short-circuit evaluation

const sampleComponent = () => {
  return isTrue && <p>True!</p>
};

For Complex scenarios with too many ternaries:

// Y soo many ternary??? :-/
const sampleComponent = () => {
  return (
    <div>
      {flag && flag2 && !flag3
        ? flag4
        ? <p>Blah</p>
        : flag5
        ? <p>Meh</p>
        : <p>Herp</p>
        : <p>Derp</p>
      }
    </div>
  )
};
  • Best approach: Move logic to sub-components
  • Alternate hacky approach: Use IIFE

There are some libraries that solve this problem (JSX-Control Statements), but rather than introduce another dependency use an IIFE and return values by using if-else statement inside

const sampleComponent = () => {
  return (
    <div>
      {
        (() => {
          if (flag && flag2 && !flag3) {
            if (flag4) {
              return <p>Blah</p>
            } else if (flag5) {
              return <p>Meh</p>
            } else {
              return <p>Herp</p>
            }
          } else {
            return <p>Derp</p>
          }
        })()
      }
    </div>
  )
};

With an appropiate transpiler you can take advantage of the upcoming do expression which is currently on stage-1

const sampleComponent = () => {
  return (
    <div>
      {
        do => {
          if (flag && flag2 && !flag3) {
            if (flag4) {
              <p>Blah</p>
            } else if (flag5) {
              <p>Meh</p>
            } else {
              <p>Herp</p>
            }
          } else {
            <p>Derp</p>
          }
        }
      }
    </div>
  )
};

Or alternatively simply use early returns

const sampleComponent = () => {
  const basicCondition = flag && flag2 && !flag3;
  if (!basicCondition) return <p>Derp</p>;
  if (flag4) return <p>Blah</p>;
  if (flag5) return <p>Meh</p>;
  return <p>Herp</p>
}

Related links: