Skip to content

Instantly share code, notes, and snippets.

@frankfaustino
Created January 25, 2018 01:17
Show Gist options
  • Save frankfaustino/56a1a9638511a099b1edf339ac4c9cff to your computer and use it in GitHub Desktop.
Save frankfaustino/56a1a9638511a099b1edf339ac4c9cff to your computer and use it in GitHub Desktop.
Funky JSX Conditionals
// 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