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>
<h1 if={this.state.age % 2 === 0}>I'm {this.state.age} year's old.</h1>
<input
type="number"
placeholder="Age"
onChange={this.ageChangeHandler}
/>
</div>
)}
}
Edit your .babelrc file:
{
"plugins": [
"jsx-if-directive",
{
"attrName": "r-if"
}
]
}
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>
<h1 r-if={this.state.age % 2 === 0}>I'm {this.state.age} year's old.</h1>
<input
type="number"
placeholder="Age"
onChange={this.ageChangeHandler}
/>
</div>
)}
}