Artboard 16light, inspiration, solution, idea, innovation,ionicons-v5_logosGoogle Sheets iconSwift icon
Published at
Updated at
Reading time
1min

After using Vue and Angular.js (I used the first version of Angular when it came out) for many years, I have to say that I always enjoyed the simplicity of using v-if and ng-if to render child components conditionally.

Now I'm writing React primarily and I'm bothered by the constant use of ternary operators when dealing with conditionally rendered components.

function SomeComponent({condition}) {
  return <div>
    { condition ? <span>Yes it is true!</span> : null }
  </div>
}

It's not a big deal, and there are many different ways to render boolean-dependent components (such as using &&), but I never really liked writing code like this and I don't think it's very readable.

Today I read 7 Ways of Achieving Conditional Rendering in React, and it included a handy snippet that I'll adopt from now on.

A conditional if component

I can't say that I didn't consider abstracting the ternary operators away, but somehow I never took it into practice. Fernando Doglio's article now moved me over the line to adopt a nicer pattern. Say hi to the functional if component.

function IF({children, condition}) {
  if (condition) {
    // render children if the condition is truthy
    return children;
  }

  return null;
}

/**
 * Use the component as follows:
 *
 * <IF condition={condition}>
 *   <Greeter username={user.name} />
 * </IF>
 */

It's seven lines of code and this tiny component can be brought into any React project as a handy utility. Much better! Thank you Fernando!

Was this snippet helpful?
Yes? Cool! You might want to check out Web Weekly for more snippets. The last edition went out 14 days ago.

Related Topics

Related Articles