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!

If you enjoyed this article...

Join 5.5k readers and learn something new every week with Web Weekly.

Web Weekly — Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles