4 ms·
The reason OP's complaint is a bit silly is because JSX is just JavaScript and there's no need to be doing everything in a single JSX expression in the first pl
by exogen 9y ago
The reason OP's complaint is a bit silly is because JSX is just JavaScript and there's no need to be doing everything in a single JSX expression in the first place. That would be bad code just like any other situation. Do what you'd do in normal JavaScript code: use multiple statements and put the conditional elsewhere. Given complicated conditionals, an experienced React dev would do:
render() {
let foo
if (someCondition) {
foo = <ChildFoo/>
}
return (
<Bar>
{foo}
</Bar>
)
}
or:
renderChildFoo() {
if (someCondition) {
return <Foo/>
}
}
render() {
return (
<Bar>
{this.renderChildFoo()}
</Bar>
)
}
or if possible, always render <Foo/> and conditionally return null in Foo's own render() method.
- couchand 9y ago> JSX is just JavaScript No, it's not. It's the bastard child of XML and JavaScript. I agree that your examples are about the best you can do with JSX. But actually just JavaScript is much easier: render() { return Bar(someCondition && Foo()) } or render() { return Bar(someCondition ? Foo() : null) } That's not quite hyperscript but it's not far from it.
- AnkhMorporkian 9y agoI believe the OP was saying that JSX is transformed into pure javascript, not that it's literally javascript.
- exogen 9y agoDigs at JSX aside, I think you may have lost track of what this thread was about: complicated nested conditionals. These are a pain to do in a single JS expression, JSX or hyperscript or otherwise – even in your example. In JSX your simple example would look just as nice: <Bar>{someCondition && <Foo/>}</Bar>