Let’s repair ternary in React JSX

The ternary operator (x ? y : z) is claimed to set off OCD in well-cultured programmers from the day it got here into React JSX. It’s the present defacto method of rendering react elements conditionally. What if we summary this bizarre syntax and have a pleasant interface to render issues conditionally.

Let’s spin up a small Subsequent.js software which exhibits a message on display if the generated random quantity is even.

Within the following snippet, you’ll see the frequent method to render utilizing the ternary operator:

Original code

🙁 The humorous and bizarre syntax presentation from traces 9 to 13 kills my temper each time I see it.

Right here comes our devoted element on the ninja cleansing mission:

RenderIf component
Refactored and Happy codeRefactored and Joyful code.



What we achieved is “Deal with to eyes” if nothing else. Additionally, now we’ve a regular method of dealing with conditional rendering all through the appliance utilizing this reusable element. Effectively, trying again, it appears humorous that we removed ternary by writing a ternary. Irony!

Shall be posting such micro articles on numerous day-to-day hacks. Keep tuned!

To Join


🏭 LinkedIn: https://www.linkedin.com/in/sameerkumar1612

✍️ Observe on Medium: https://sameer-kumar-1612.medium.com

Add a Comment

Your email address will not be published. Required fields are marked *