Created
January 25, 2018 01:17
-
-
Save frankfaustino/56a1a9638511a099b1edf339ac4c9cff to your computer and use it in GitHub Desktop.
Funky JSX Conditionals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Good ol' ternary | |
<div>{condition ? <span /> : null}</div> | |
// AND | |
<div>{condition && <span />}</div> | |
// Multiple elements | |
<div>{condition ? [<span />, <span />] : null}</div> | |
// Text nodes | |
<div>{condition ? 'Hello ' + name + '!' : null}</div> | |
// Things get messy | |
<div>{condition ? [<span />, 'Hello ' + name + '!', <span />] : null}</div> | |
// Now it's just ugly | |
<div> | |
{condition | |
? [ | |
(condition ? [<span />, 'My name is ' + name + '!', <span />] : null), | |
'Hello ' + name + '!' | |
] | |
: null} | |
</div> | |
// As a stateless component | |
<div> | |
<listSpans condition={condition} /> | |
</div> | |
function listSpans(props) { | |
if (!props.condition) return null | |
return [<span />, <span />] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment