/babel-plugin-react-directives

A babel plugin that provides some directives for react(JSX), similar to directive of vue.

Primary LanguageJavaScriptMIT LicenseMIT

babel-plugin-react-directives

A babel plugin that provides some directives for react(any JSX), similar to directive of vue.

Travis (.org) branch Codecov node npm GitHub

🇨🇳 中文文档

Table of Contents

Usage

Requires node v8.6.0 or higher, babel v6.20.0 or higher.

Installation

use npm:

npm install --save-dev babel-plugin-react-directives

use yarn:

yarn add --dev babel-plugin-react-directives

Configuring via .babelrc

{
  "plugins": [
    "react-directives"
  ]
}

Or use options (Babel plugin options)

{
  "plugins": [
    [
      "react-directives",
      {
        "prefix": "x",
        "pragmaType": "React"
      }
    ]
  ]
}
  • prefix: JSX props prefix for directives. Default: "x", usage example: x-if
  • pragmaType: Help internal to correctly identify some syntax, such as hooks. Default: "React"

Directives

x-if

If the x-if value is truthy, this element will be rendered, otherwise do not.

Example:

const foo = <div x-if={true}>text</div>

Convert to:

const foo = true ? <div>text</div> : null

x-else-if and x-else

The x-else-if must have a corresponding x-if. if x-if value is falsy, and x-else-if value is truthy, it will be rendered.

The x-else must have the corresponding x-if or x-if-else. When all corresponding x-if or x-else-if value are falsy, it will be rendered.

Example:

const foo = (
  <div>
    <p x-if={data === 'a'}>A</p>  
    <p x-else-if={data === 'b'}>B</p>  
    <p x-else-if={data === 'c'}>C</p>  
    <p x-else>D</p>  
  </div>
)

Convert to:

const foo = (
  <div>
    {data === 'a' 
      ? <p>A</p> 
      : data === 'b' 
        ? <p>B</p> 
        : data === 'c' 
          ? <p>C</p> 
          : <p>D</p>
    }
  </div>
)

x-show

The x-show controls the display or hiding of elements by the display of the style prop. If the x-show value is falsy, will set style.display = "none", otherwise do nothing.

Example:

const foo = <div x-show={true}>text</div>

Convert to:

const foo = (
  <div style={{
    display: true ? undefined : "none"
  }}>text
  </div>
)

Of course, it will also merge other style by calling the runtime function, for example:

const foo = (
  <div 
    style={{ color: 'red' }}
    x-show={true} 
    {...extraProps}>
    text
  </div>
)

will be converted to:

const foo = (
  <div
    {...extraProps}
    style={{
      ...require("babel-plugin-react-directives/lib/runtime").mergeProps.call(this, "style", [
        { style: { color: 'red' } },
        extraProps
      ]),
      display: true ? undefined : "none"
    }}>text
  </div>
)

x-for

The x-for is used to traverse arrays to generate elements.

The value should like: (item, index) in list

  • list: array for traversal
  • item: current value
  • index: current index (optional)

Note: If you use ESLint, you may receive an error that item and index are undeclared variables. Please install eslint-plugin-react-directives plugin to solve it.

Example:

const foo = (
  <ul>
    <li 
      x-for={item in list}
      key={item.id}>{item.name}
    </li>
  </ul>
)

Convert to:

const foo = (
  <ul>
    {list.map(item => (
      <li key={item.id}>{item.name}</li>
    ))}
  </ul>
)

Also note that if used with x-if, the x-for has a higher priority, for example:

const foo = (
  <ul>
    <li
      x-for={item in list}
      x-if={item.name === 'alice'}
      key={item.id}>{item.name}
    </li>
  </ul>
)

will be converted to:

const foo = (
  <ul>
    {list.map(item => (
      item.name === 'alice' 
        ? <li key={item.id}>{item.name}</li> 
        : null
    ))}
  </ul>
)

x-model

The x-model is a syntax sugar similar to vue v-model, which binds a state to the value prop of the form element and automatically updates the state when the element is updated. It resolves the updated value by calling the runtime function (If the first argument arg is non-empty, and arg.target is an object, return arg.target.value, otherwise return arg).

Example:

class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = { data: 'text' }
  }
  
  render() {
    return <input x-model={this.state.data}/>
  }
}

Convert to:

class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = { data: 'text' };
  }

  render() {
    return (
      <input value={this.state.data} onChange={(..._args) => {
        let _value = require("babel-plugin-react-directives/lib/runtime").resolveValue(_args);

        this.setState(_prevState => {
          return { data: _value };
        });
      }}/>
    );
  }
}

When there are other onChange props, merge them by calling the runtime function:

class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = { data: 'text' }
  }
  
  onChange(e) {
    console.log(e.target.value);
  }
  
  render() {
    return (
      <input
        onChange={this.onChange.bind(this)}
        x-model={this.state.data}
        {...this.props}
      />
    ) 
  }
}

will be converted to:

class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = { data: 'text' };
  }

  onChange(e) {
    console.log(e.target.value);
  }

  render() {
    return (
      <input
        {...this.props}
        value={this.state.data}
        onChange={(..._args) => {
          let _value = require("babel-plugin-react-directives/lib/runtime").resolveValue(_args);

          this.setState(_prevState => {
            return { data: _value };
          });

          require("babel-plugin-react-directives/lib/runtime").invokeExtraOnChange.call(this, _args, [
            { onChange: this.onChange.bind(this) },
            this.props
          ]);
        }}/>
    );
  }
}

If the x-model value is an object's property, a new object is created when it is updated, and the object's old property values are merged. For example:

class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {
        text: 'bar'
      }
    }
  }

  render() {
    const { data } = this.state;
    return <input x-model={data.text}/>
  }
}

will be converted to:

class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: { text: 'bar' }
    };
  }

  render() {
    const { data } = this.state;
    return (
      <input
        value={data.text}
        onChange={(..._args) => {
          let _value = require("babel-plugin-react-directives/lib/runtime").resolveValue(_args);

          this.setState(_prevState => {
            let _val = {
              ..._prevState.data,
              text: _value
            };
            return { data: _val };
          });
        }}
      />
    );
  }
}

x-model-hook

The x-model-hook is similar to the x-model, the difference is that the x-model-hook is used in the useState hook function, and the x-model is used in the class component.

Example:

function Foo() {
  const [data, setData] = useState(0);
  return <input x-model-hook={data}/>
}

Convert to:

function Foo() {
  const [data, setData] = useState(0);
  return (
    <input
      value={data}
      onChange={(..._args) => {
        let _value = require("babel-plugin-react-directives/lib/runtime").resolveValue(_args);

        setData(_value);
      }}
    />
  );
}

Note: If you use ESLint, you may receive an error that setData is defined but never used. Please install eslint-plugin-react-directives plugin to solve it.

Related Packages

Known Issues

  • When using x-for in Typescript, the binding value item will report an error. The temporary solution is to declare the item variable before use. Such as declare let item: any. And it is not recommended to use x-for in Typescript.

CHANGELOG

See more information at: CHANGELOG

LICENSE

MIT