DEV Community

Cover image for Better Conditional Rendering with Is.js
Patrick Jones
Patrick Jones

Posted on • Edited on

Better Conditional Rendering with Is.js

What is Conditional Rendering

Conditional rendering as a term describes the ability to render different UI markup based on certain conditions. In React-speak, it is a way to render different elements or components based on a condition. This concept is applied often in the following scenarios:

  • Rendering external data from an API
  • Showing/hiding elements
  • Toggling application functionality
  • Implementing permission levels
  • Authentication and Authorization

Problems With Readability

Take the UserInfo component as an example. The user object must be populated with data before the h1 can be rendered. To achieve this, a Logical && is used to block the right hand side of the expression from being rendered if the left hand side is fails to meet a condition. This is also known as Short Circuit Evaluation.

function UserInfo({user}) {
  return (
    (user !== {}) && <h1>{user.name}</h1>
  )
}

While this format gets the job done, it can lead developers astray when trying to quickly infer the 'meaning' of a component. The problem is especially evident when rendering is dependent on array length.

function UsersList({users}) {
    return (
        (users && users.length > 0) &&
            users.map(user => <UserInfo user={user} />)
    )
}

This is objectively ugly and the nested && operators are just as bad as nested ternaries.

A Convenient Solution

Is.js is a micro-library that, at only 4kb when gzipped, solves this readability issue without adding much to an application's total package size. It comes packed with plenty of features, but I'll only be focusing on the parts that lend themselves to making conditional rendering more declarative and easy to read.

To get started, install is.js in your app:

npm install is_js

Now you can include is_js in any file.

// src/app.js
import React from "react"
import is from "is_js"
...

Examples

Check for Emptiness

function UserInfo({user}) {
    return (
        is.not.empty(user) &&
            <h1>{user.name}</h1>
    )
}
function UsersList({users}) {
    return (
        is.not.empty(users) &&
            users.map(user => <UserInfo user={user} />)
    )
}

The intentions of this code are much more apparent because they are immediately readable by a developer. No interpretation required.

Top comments (0)