Cleaner way to write conditionals in JSX

Hardik khanchandani
Tech @ Trell
4 min readOct 30, 2021

--

Hello, I’m Hardik and this is my first blog. I am an SDE intern at Trell🐱‍💻 working on Trell Shop. I am involved in the rewrite of the Trell Shop web app to the Nextjs app. In the new web codebase, we are focusing on a lot of Optimizations, Clean and Readable code.

This blog is about increasing the readability of JSX.

Problem

Conditionals in JSX make codes messy and less readable. See the issue in this Stackoverflow issue. If the codebase is large enough and there is a lot of conditions and logic for JSX things will get out of hand pretty sooner.

I don’t want my code to look like this or similar alternatives, NEVER. We have a similar situation in Add to cart button let me show you how the code looks like in the old codebase (mock).

So initially, we should show Add to Cart in the button if a user sees it for the first time. When a user clicks on it, it should show ‘loading..’ while we are processing info. After that if a user is logged in then we should show View Bag: ₹ 900 else we want to show Login to view bag(took this case to show the scalability of new readable code). But if the product is out of stock we want to show OUT OF STOCK.

So can you understand all of this by looking at the code? At least I can’t in one go.

The solution

Below is the code that is more readable Inspired by jsx-control-statements . I will show you some good patterns in JSX which can help make JSX cleaner and readable.

If component is understandable by its name and really easy to implement, Choose When Otherwise the pattern is like switch case default, When acts as case with the condition and Otherwise acts at default case if nothing works.

Let’s start with easy.

Liked it? Lemme show you a more interesting pattern. This is Called Choose Element. You can use it from here. Let me show you how you can implement it. (not a perfect implementation, just enough to explain you a concept, you can use it from the plugin)

First When component with the true condition will be returned.

Output: I want Tea

Use-case of Otherwise Component

So if none of the When components has the true condition, Otherwise component will be Chosen

Output: Tea/Coffee + Sandwich

Let’s start with easy and build When and Otherwise components.

Pretty easy! The real game is Choose now. Let's go ahead and implement this Choose component. Choose component will look for the first When component with the condition prop as true and return that from Choose component. If no When component has a true condition. We will look for Otherwise component and return it.

Partial implementation of Choose component

I hope you liked it. Patterns are opinionated. You may like this or not depending on you. Thanks for reading. 😄

Designs by Astha

--

--