Skip to main content

Command Palette

Search for a command to run...

Clean conditional layouts in React

Updated
1 min read
Clean conditional layouts in React

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>
I
Iva Kop5y ago

I really like that approach! Thanks for sharing 🌟

T

Thanks Iva. I'm pretty happy with it too ☺️

D

I see your point. Easy for a beginner in React to understand the Condition Component of course. Beautiful!

T

Thanks Darlan 🙏