0.0.7 • Published 5 years ago

reactive.macro v0.0.7

Weekly downloads
3
License
MIT
Repository
-
Last release
5 years ago

Travis (.org) branch

A babel macro that helps you reduce the React boilerplate.

Installation

$ npm install reactive.macro --save

You need babel-plugin-macros before using this package.

If you are using create-react-app, it's already 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(0);
  const [b, setB] = useState(1);

  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 bye state macro.

Example

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

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

License

MIT

0.0.7

5 years ago

0.0.6

5 years ago

0.0.5

5 years ago

0.0.4

5 years ago

0.0.3

5 years ago

0.0.2

5 years ago

0.0.1

5 years ago

0.0.1-alpha.5

5 years ago

0.0.1-alpha.3

5 years ago

0.0.1-alpha.2

5 years ago

0.0.1-alpha.1

5 years ago

0.0.1-alpha.0

5 years ago