yesmeck / reactive.macro

Reduce React boilerplate.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

reactive.macro logo

GitHub Workflow Status

A babel macro that helps you reduce the React boilerplate.

Installation

$ npm install reactive.macro --save

babel-plugin-macros is required before using this package.

If you are using create-react-app, it has included babel-plugin-macros.

Usage

import React from 'react';
import { state, bind } from 'reactive.macro';

export default () => {
  let a = state(1);
  let b = state(2);

  return (
    <div>
      <input type="number" value={bind(a)} />
      <button onClick={b => b += 1} >b+</button>

      <p>{a} + {b} = {a + b}</p>
    </div>
  );
};

See live demo.

Equals:

import React, { useState, useCallback } from 'react';

export default () => {
  const [a, setA] = useState(1);
  const [b, setB] = useState(2);

  return (
    <div>
      <input type="number" value={a} onChange={useCallback(e => setA(e.target.value), [])} />
      <button onClick={b => setB(b + 1)} >b+</button>

      <p>{a} + {b} = {a + b}</p>
    </div>
  );
};

API

state

Declare a state.

Arguments

  • initialState - Initial value.

Example

In component:

const App = () => {
  let count = state(0);

  return <button onClick={() => count + 1}>Clicked {count} {count > 1 ? 'times' : 'time'}</button>
}

In custom hook:

const useToggle = () => {
  let visible = state(false);

  const toggle = () => {
    visible = !visible
  }

  return [visible, toggle];
}

You can update the value of count directly without calling setState.

Note: using array methods like push and splice won't trigger re-render. Instead you can use spread syntax.

let users = state([]);

const addUser = (user) => {
  users = [...users, user];
}

bind

Bind a state to a form control.

  • state - The state which is declared by state macro.

Example

const App = () => {
  let name = state('');

  return (
    <div>
      <input value={bind(name)} />
      Hello {name}!
    </div>
  );
}

License

MIT

About

Reduce React boilerplate.

License:MIT License


Languages

Language:TypeScript 94.0%Language:JavaScript 6.0%