Write nice and clean if statements in React JSX code
I have always enjoyed making things more simple and more understandable. This story will not contain any breaking changes of coding JSX. But it can makes life easier when working with it.
I think JSX is nice and simple but when it comes to its syntax it can be quite confusing. The problem is, as i see it, that you often need to mix javascript and XML-look-a-like syntax, for example when you need to write an if-statement embedded in the JSX code.
Of course, the best way is to avoid logic in the template but sometimes it may generate overloaded code just because of the strive to follow guidelines.
So, i wrote a component (lb-jsx-if-statement) to make this easier to handle. And i am happy to share it with you and this idea of structuring JSX.
The component does no magic at all. It is just about making a component look like a javascript statement block and in the same time having a prop working as a container for the statement. The component will return its children if the prop value is true. Otherwise not. If you now take a look at the node tree, you will see a much more clean one where the component will act like an If-statement.
There you see, no magic. Just a way of returning (or not returning) JSX nodes in certain conditions.
There are downsides, thou. There is no way to use elseIf or else. But if you’re ending up with massive statements in the JSX parts of your code, you probably is not doing it right, anyway.
import { If } from 'lb-jsx-if-statements'
const Component = myVar => (
<div>
<If statement={myVar === 'foo' || myVar === 'bar' }>
<div>
Foo bar.
</div>
</If>
</div>
)
<Component myVar="foo" />
<Component myVar="bar" />
<Component myVar="something falsy" />Enjoy!
