How To Make Conditional Logic Within Your React JSX Components More Declarative

In this tutorial, you will learn about a free component you can choose to use within your react.js projects that can help make your code a little more easier (declarative).  In this tutorial, you will learn a little bit about render-if.  Render-if is a small curried function that allows you to strip out some of the ugly conditional code within your JSX and replace it with a more human-readable format.  If having easier to understand code sounds good to you, then read on.

Render-if

Before we begin, I think it's good to start off saying some readers may disagree with using a nice-to-have third-party package in their code.  Some folks will have stronger preferences to having control over as much code in their project as possible, or, they have security concerns.  

These are all valid concerns, but, personally, I tend to favour using battle-proven components that have been used by thousands of people, rather than trying to re-invent the wheel. 

My personal thought-pattern to react components is that one of the underlining patterns of React and JSX are based on functional programming principles.  Splitting big pages into smaller well-defined components/functions is the goal in order to write cleaner code.  Following that thought process, render-if fits nicely into it. 

Render-if does pretty much exactly what you think it will do.  Render-if is a curried function you can import into your components, that takes a logical predicate and a function, and will render the function if the predicate evaluates to true.  In simple speak, it allows you to do render-if statements within your components in a more human-readable way, cool hey? You can add render-if to your project, using:

npm add render-if

After you have it installed, you can use it like this:

renderIf(2 * 2 === 4)(
  <div>Display Me</div>
)

Or a little nicer:

      {renderIf(2 * 2 === 4))(() => (
          <div>Display Me</div>
      ))}

You can also compose it in, so you can move your logic to the top of your render method, rather than doing it within your return to make things even cleaner.

      const ifTrue = number => renderIf(true);
 
      {ifTrue()(
          <div>Display Me</div>
      )} 

That's pretty much all you need to know. If you are building react components then I recommend you check this package out. It takes all of 5 minutes to figure out and for complex components that contain a lot of logic, this can definitely help make your code easier to read. Enjoy!

 

submit to reddit

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

Back to top