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 React.Component {
constructor(props) {
super(props);
this.ageChangeHandler = this.ageChangeHandler.bind(this);
this.state = {
age: 21
}
}
ageChangeHandler(e) {
this.setState({
age: e.target.value
})
}
render() { return (
<div>
<p>Hi, I'm {this.state.age} year's old.</p>
<p if={this.state.age % 2 === 0}>And it's an even number!</p>
<p else>And it's an odd number!</p>
<input
type="number"
placeholder="Age"
onChange={this.ageChangeHandler}
/>
</div>
)}
}
Edit your .babelrc file:
{
"plugins": [
"jsx-if-directive",
{
"ifAttrName": "r-if",
"elseAttrName": "r-else"
}
]
}
In your jsx file:
class App extends React.Component {
constructor(props) {
super(props);
this.ageChangeHandler = this.ageChangeHandler.bind(this);
this.state = {
age: 21
}
}
ageChangeHandler(e) {
this.setState({
age: e.target.value
})
}
render() { return (
<div>
<p>Hi, I'm {this.state.age} year's old.</p>
<p r-if={this.state.age % 2 === 0}>And it's an even number!</p>
<p r-else>And it's an odd number!</p>
<input
type="number"
placeholder="Age"
onChange={this.ageChangeHandler}
/>
</div>
)}
}