@web-companions/gfc
v2.4.0
Published
Generator Functional Components. A wrapper for creating Web components through JS Generator function
Downloads
14
Readme
Generator Functional Components. A wrapper for creating Web components with JS Generator function
Features
- 🚀 Fast: Built with standards based Custom Elements and JS Generator.
- 🪂 Typed: Written in TypeScript.
- ⚛️ JSX: Can be used with JSX or without it (babel-plugin-transform-jsx-to-tt).
- 🪢 Flexible: Fit to different template libraries.
- 🧹 No dependencies
Table of contents
Installation
npm install @web-companions/gfc --save
Usage
For the best DX I suggest using this library with babel-plugin-transform-jsx-to-tt and lit-html or another library to rendering templates to DOM.
index.jsx
import { EG, p } from '@web-companions/gfc';
import { render } from 'lit-html';
/**
* Counter element
*/
export const counterElement = EG({
props: {
msg: p.req<string>(),
},
})(function* (props) {
let count = 0;
while (true) {
props = yield render(
<>
<button
type="button"
onclick={() => {
count++;
this.next();
}}
>
{props?.msg}
</button>
<i>{count}</i>
</>,
this
);
}
});
// define a new custom Counter element with tag 'demo-counter-element'
const CounterElement = counterElement('demo-counter-element');
/**
* ROOT element
*/
EG({
props: {
header: p.req<string>('header'),
},
})(function* (props) {
while (true) {
props = yield render(
<div
style={css`
margin: 10px;
`}
>
<h3>{props.header}</h3>
<CounterElement msg={'Counter Element'}></CounterElement>
</div>,
this
);
}
})('demo-fc');
More examples are here.
Notice
Node view
- This type of view could be created only inside an Element view.
- If some of Node view will be rendered by a condition we should create them with prepared ref objects. Otherwise, some of Nodes can start to use the same inner state.