Clean conditional layouts in React

Clean conditional layouts in React

Featured on Hashnode

Making conditional sections of markup in React is usually achieved by breaking into code blocks with ternaries or logical operators. That can make a layout hard to follow at a glance. It might even prompt you to break components down to avoid adding logic to the render block, which can add needless over-composition and bloated component hierarchies.

For my projects, I've introduced a simple fragment component to alias logical operators, allowing uninterrupted markup. Now I can avoid making composition decisions based on code style.

With Conditional

import { FC } from 'react'

export const Conditional: FC<{ when: boolean }> = ({ when, children }) => <>{(when) && children}</>

Usage

<Box>
  <Conditional when={isLoading}>
    Loading...
  </Conditional>
  Other stuff.
</Box>

Vs

<Box>
  {isLoading && (
    <>
      Loading...
    </>
  )}
  Other stuff.
</Box>