0.1.3 • Published 5 years ago

babel-plugin-jsx-if-directive v0.1.3

Weekly downloads
34
License
MIT
Repository
github
Last release
5 years ago

Using "if" directive in JSX

GitHub stars GitHub forks npm npm npm

A easy-to-use "if" directive solution for front-end frameworks using JSX like React.

See Also:

1. Install

npm install --save-dev babel-plugin-jsx-if-directive

2. Basic Usage

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>
        )
    }
}

3. Usage with custom attribute name

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>
        )
    }
}