DEV Community

Discussion on: Simplify condition rendering in React.js

Collapse
 
christoslitras profile image
Christos Litras • Edited

IMO there is no need to create an <IF> component. For most simple cases, ternary operator <condition> ? <if-true> : <if-false> or simple boolean operators && and/or || will do the job; for something more complex, it would be better to create an additional function to render it. If we want to render it directly in place and we have many conditions/components to check, there is a new Javascript do expression (tc39/proposal-do-expressions) that is in stage 1 of the TC39 process and it will solve such problems by using some native syntax like:

const Component = props => (
  <div className="myComponent">
    {do {
      if (color === "blue") {
        <BlueComponent />;
      } else if (color === "red") {
        <RedComponent />;
      } else if (color === "green") {
        <GreenComponent />;
      }
      <DefaultColorComponent />;
    }}
  </div>
);
Enter fullscreen mode Exit fullscreen mode

We can already use it by using Babel plugin @babel/plugin-proposal-do-expressions.