Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 14, 2022 06:57 am GMT

Lets repair ternary in React JSX

The ternary operator (x ? y : z) is said to trigger OCD in well-cultured programmers from the day it came into React JSX. It is the current defacto way of rendering react components conditionally. What if we abstract this weird syntax and have a friendly interface to render things conditionally.

Let's spin up a small Next.js application which shows a message on screen if the generated random number is even.

Sample application

In the following snippet, youll see the common way to render using the ternary operator:

Original code

The funny and weird syntax presentation from lines 9 to 13 kills my mood every time I see it.

Here comes our dedicated component on the ninja cleaning mission:

RenderIf component
Refactored and Happy codeRefactored and Happy code.

Conclusion

==========

What we achieved is Treat to eyes if nothing else. Also, now we have a standard way of handling conditional rendering throughout the application using this reusable component. Well, looking back, it seems funny that we got rid of ternary by writing a ternary. Irony!

Will be posting such micro articles on various day-to-day hacks. Stay tuned!

To Connect

==========

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

Follow on Medium: https://sameer-kumar-1612.medium.com


Original Link: https://dev.to/sameer1612/lets-repair-ternary-in-react-jsx-2jem

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To