A cleaner solution for conditionals and loops in JSX using Babel 6
JSX quickly gets a bit messy when nesting conditionals or doing loops. One solution is to break it up into multiple functions or components, but that sometimes just makes it harder to follow;
<div>
{condition1 ?
[
(condition2 ?
[
<span></span>,
'My name is ' + name + '!',
<span></span>
]
: null),
'Hello ' + name + '!'
]
: <span>Something else</span>}
{myArray.map((item) => (
<div>
{item.awd}
</div>
)}
</div>
You might want to check out a little project called jsx-control-statements. It’s a Babel plugin that introduces a few virtual components that you can use in your JSX.
<div>
<Choose>
<When condition={condition1}>
<If condition={condition2}>
My name is {name}!
</If>
Hello {name}!
</When>
<Otherwise>
<span>Something else</span>
</Otherwise>
</Choose>
<For each="item" of={myArray} index="i">
<div key={i}>
{item.awd}
</div>
</For>
</div>
You don’t need to import any of the components, they are parsed by the Babel plugin and replaced with real conditionals and loops behind the scenes.
There’s even an eslint plugin that makes sure you don’t get warnings about missing imports, unset variables, and things like that.
Check out the link below for installation instructions and more information.