Add <If>
, <ElseIf>
and <Else>
to JSX using TypeScript compiler transforms.
import { If, Else, ElseIf } from 'jsx-conditionals';
<If condition={student}>
{ student.name }
</If>
<ElseIf condition={teacher}>
{ teacher.age }
</ElseIf>
<Else>
Both false
</Else>
Unlike other implementations, jsx-conditionals retains the lazy evaluation of ternary expressions.
In a naive implementation,
student.name
above would throw a 'student is not defined' error. This implementation only evaluates the necessary expressions.
You can read more about it on my blog.
Because it happens at compile-time, there's no runtime dependency at all. It's purely syntactic sugar.
Install
jsx-conditionals works by using TypeScript compiler transforms. Even though this is a native TypeScript feature, it's not yet exposed publically. You need ttypescript which is a smaller wrapper around TypeScript which exposes that feature.
npm install --save-dev jsx-conditionals ttypescript
Follow ttypescript's setup for the specific tools you're using. There is different configuration for Webpack, Rollup, Jest, etc but mostly they're just 1 or 2 lines of configuration to re-point the compiler. If you're confused, there's a full sample project using Webpack.
Then in your tsconfig.json
add the transformation:
{
"compilerOptions": {
"plugins": [
{ "transform": "jsx-conditionals/transform" },
]
}
}