I'd bet this looks absolutely crazy to many developers:
<div *ngIf="foo; then bar else baz"></div>
An essentially eval'd code string inside a markup attribute? That uses some made-up language that's neither HTML nor JS?! I used to write plenty of code like this in various template languages, and it always felt bad.JS:
const sampleComponent = () => {
return isTrue && <p>True!</p>
};
CLJS: (defn sample-component [is-true?]
(when is-true? [:p "True!"]))
Any language that has if expressions would be preferable to JS in this case, I think. <Conditional bool={true}>
<IfTrue/>
<IfFalse/>
</Conditional>
Doesn't seem any better 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.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. <Bar>{someCondition && <Foo/>}</Bar>One thing I don't like, though:
const sampleComponent = () => {
return isTrue && <p>True!</p>
};
If isTrue is 0, React will render 0. If isTrue is NaN, React will render NaN. Best to cast the conditional to boolean when using short-circuit evaluation: const sampleComponent = () => {
return !!isTrue && <p>True!</p>
};Just one line up in the bulleted list is: “Best approach: Move logic to sub-components“. There isn’t an example or a link because the recommendation is that simple.
Of course there are no absolutes and there are many other approaches that split difference between inline logic and additional components, but the general idea is to avoid writing a bunch of conditionals in your JSX unless you have to - and in that case, this mess of nested ternaries is one way to do it.
> If one needs such inelegant code to deal with basic boolean logic
You don't. Idiomatic React doesn't try and put complex logic in the JSX; the recommended approach (including in the linked article) is to do you logic in plain JS with small focused components or render functions.
<div>
{flag && flag2 && !flag3
? flag4
? <p>Blah</p>
: flag5
? <p>Meh</p>
: <p>Herp</p>
: <p>Derp</p>
}
</div>
Should be: <div>
{ flag && flag2 && !flag3
? flag4
? <p>Blah</p>
: flag5
? <p>Meh</p>
: <p>Herp</p>
: <p>Derp</p>
}
</div>this example should just be using early returns imo
added a PR: https://github.com/vasanthk/react-bits/pull/76/files