12 ms·
> And finally, what stops you from creating a custom component that works like this? I wondered what the issue was myself, so I actually implemented that patte
by dismantlethesun 10y ago
> And finally, what stops you from creating a custom component that works like this?
I wondered what the issue was myself, so I actually implemented that pattern in a codepen, then looked at the compiled form of the JSX to Javascript.
The essential issue is that the value of a prop is always evaluated at runtime, regardless of if the prop is actually used. In the case of props.children this means that <Then> and <Else> are both evaluated, and thus rendered, and only one of them is actually used.
Thus you can't have conditionally rendering children, unless you've written them to be okay with failing at a render, with a blanket state---which is what most people are trying to avoid writing into their components, and simply want to conditionally render in a higher level component.
- Keithamus 10y agoWrapping them in methods is an easy way to fix that... but not sure if it is any cleaner. render() { return <If cond={ this.state.loggedIn } then={() => `Hello ${ this.state.userName }`} else={() => `Please log in` } /> }
- spion 10y agoOr with an algebraic Maybe data type {this.state.user.case({ some: user => `Hello ${ user.name }` none: () => `Please log in` })} Or for async requests that are in progress, an algebraic 3-state type: https://twitter.com/Tholle1234/status/804796967222202372 https://twitter.com/Tholle1234/status/804796967222202372
- Untit1ed 10y agoYou can get around it with a Babel transform: https://www.npmjs.com/package/jsx-control-statements https://www.npmjs.com/package/jsx-control-statements Disclosure: self-promotion. It's really frustrating that I see this React-is-crap-because-no-conditionals come up again and again but if you want them all it takes is an npm install and a line of babel config :(.
- flopsey 10y agoThe article doesn't bash react, but it does say that Vue's ability to use conditionals is superior.
- eyko 10y agosince then and else are going to be used inside an if component, you can use context to read condition, then not render at all if you don't need to (return null).