0.0.7 • Published 7 years ago
reactive.macro v0.0.7
A babel macro that helps you reduce the React boilerplate.
Installation
$ npm install reactive.macro --saveYou 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 byestatemacro.
Example
const App = () => {
let name = state('');
return (
<div>
<input value={bind(name)} />
Hello {name}!
</div>
);
}License
0.0.7
7 years ago
0.0.6
7 years ago
0.0.5
7 years ago
0.0.4
7 years ago
0.0.3
7 years ago
0.0.2
7 years ago
0.0.1
7 years ago
0.0.1-alpha.5
7 years ago
0.0.1-alpha.3
7 years ago
0.0.1-alpha.2
7 years ago
0.0.1-alpha.1
7 years ago
0.0.1-alpha.0
7 years ago