✨ Stateful functional React components without runtime overhead (inspired by ClojureScript) ✨
Compiles stateful functional React components syntax into ES2015 classes
WARNING: This plugin is experimental. If you are interested in taking this further, please open an issue or submit a PR with improvements.
Because functional components are concise and it's annoying to write ES2015 classes when all you need is local state.
- No runtime overhead
- No dependencies that adds additional KB's to your bundle
Input
const Counter = ({ text }, { val } = { val: 0 }, setState) => (
<div>
<h1>{text}</h1>
<div>
<button onClick={() => setState({ val: val - 1 })}>-</button>
<span>{val}</span>
<button onClick={() => setState({ val: val + 1 })}>+</button>
</div>
</div>
);
Output
class Counter extends React.Component {
constructor() {
super();
this.state = { val: 0 };
}
render() {
const { text } = this.props;
const { val } = this.state;
return (
<div>
<h1>{text}</h1>
<div>
<button onClick={() => this.setState({ val: val - 1 })}>-</button>
<span>{val}</span>
<button onClick={() => this.setState({ val: val + 1 })}>+</button>
</div>
</div>
);
}
}
- The second parameter (state) must be assigned default value (initial state)
- The third parameter must be named
setState
npm i babel-plugin-stateful-functional-react-components
.babelrc
{
"plugins": ["stateful-functional-react-components"]
}
babel --plugins stateful-functional-react-components script.js
require("babel-core").transform("code", {
plugins: ["stateful-functional-react-components"]
});
MIT