A easy-to-use "if" directive solution for front-end frameworks using JSX like React.
See Also:
- Using two-way data binding in JSX: babel-plugin-jsx-two-way-binding
- Using for-directive in JSX: babel-plugin-jsx-for-directive
npm install --save-dev babel-plugin-jsx-if-directive
Edit your .babelrc file:
{
"plugins": [
"jsx-if-directive"
]
}
In your jsx file:
class App extends Component {
constructor() {
super();
}
state = {
age: 0
}
plus = () => {
const { state: { age } } = this;
this.setState({ age: age + 10 });
}
render() {
const { age } = this.state;
return (
<div>
<button onClick={this.plus}>+</button>
<h1 if={age < 18}>You are child.</h1>
<h1 elseIf={age < 40}>You are youth.</h1>
<h1 elseIf={age < 60}>You are middle-aged.</h1>
<h1 else>You are old man.</h1>
<p>You are {age} years old</p>
</div>
)
}
}
Edit your .babelrc file:
{
"plugins": [
"jsx-if-directive",
{
"ifAttrName": "r-if",
"elseAttrName": "r-else",
"elseIfAttrName": "r-elif"
}
]
}
In your jsx file:
class App extends Component {
constructor() {
super();
}
state = {
age: 0
}
plus = () => {
const { state: { age } } = this;
this.setState({ age: age + 10 });
}
render() {
const { age } = this.state;
return (
<div>
<button onClick={this.plus}>+</button>
<h1 r-if={age < 18}>You are child.</h1>
<h1 r-elif={age < 40}>You are youth.</h1>
<h1 r-elif={age < 60}>You are middle-aged.</h1>
<h1 r-else>You are old man.</h1>
<p>You are {age} years old</p>
</div>
)
}
}