Another way to write conditional stuff in React

Indie Dev
Dec 22, 2021

--

Photo by Viktor Talashuk on Unsplash

When developing frontend apps, we can face a lot of codes that using conditional stuff like below

login ? 
(user.isSuperAmdin ? <div>Super Admin</div> : <div>User</div>)
: <div>Log in</div>

We can re-write it by introducing the Condition components like If/Switch

<If condition={login}>
<If condition={user.isSuperAdmin}>
<div>Super Admin</div>
<Otherwise>Normal User</Otherwise>
</If>
<Otherwise>Login</Otherwise>
</If>

Another case for Switch component

{tabIndex === 0 && renderTab0Content()}
{tabIndex === 1 && renderTab1Content()}
{tabIndex === 2 && renderTab2Content()}

We can rewrite like

<Switch comparingValue={tabIndex}>
<Case value={0}>
{renderTab0Content()}
</Case>
<Case value={1}>
{renderTab1Content()}
</Case>
<Case value={2}>
{renderTab2Content()}
</Case>
<Otherwise>
<div>Oh no we dont support here</div>
</Otherwise>
</Switch>

With this approach, I think we can see the code clearer — it likes a DSL way to explain the code flow.

What do you think about this way?

Welcome any feedback and ideas. Thanks.

--

--

Indie Dev
Indie Dev

No responses yet