Componentes
Component composition
Component
Create a new custom web component with the api: component(name, setup)
.
- name:** Name of the HTML tag of the component (must comply with the format:
lowercase-words
). - setup: Function that is executed when the component is initialized; it receives the properties and must return a view (using
html
).
javascript
component("my-component", () => {
// setup code
return html`...`,
});
// Factory Class HTMLElement
// –––––––––––––––––––––––––
// |
// v
component("my-component", (props) => {
// ^ ^
// HTML tag name properties
// ––––––––––––– ––––––––––
//
// (Component definition here ... )
return html`...`, // return view
});
Properties
The component properties are received in the props parameter or can be unstructured. These properties come from the attributes defined in the HTML.
javascript
import { component, html } from "esor";
component("user-card", (props) => {
return html`
<div class="card">
<h3>${props.name}</h3>
<p>${props.email}</p>
</div>
`;
});
with destruction:
javascript
import { component, html } from "esor";
component("user-card", (props) => {
const { name, email } = props;
return html`
<div class="card">
<h3>${name}</h3>
<p>${email}</p>
</div>
`;
});
You can also destructure directly:
javascript
import { component, html } from "esor";
component("user-card", ({ name, email }) => {
return html`
<div class="card">
<h2>My User Card</h2>
<p>${name}</p>
<p>${email}</p>
</div>
`;
});
Using the this
context:
javascript
import { component, html } from "esor";
component("user-card", function () {
return html`
<div class="card">
<h2>My User Card</h2>
<p>${this.props.name}</p>
<p>${this.props.email}</p>
</div>
`;
});
Usage:
html
<user-card name="Juan" email="juanonexample.com"></user-card>
Emit to parent
javascript
component("happy-app", () => {
const isHappy = signal(true);
const handleNo = () => isHappy(false);
const handleYes = () => isHappy(true);
return html`
<div style="margin:16px 0">
<h2>Are you happy?</h2>
<p style="font-size: 50px">${() => (isHappy() ? "😀" : "😥")}</p>
<answer-button onno=${handleNo} onyes=${handleYes}></answer-button>
</div>
`;
});
component("answer-button", function () {
return html`
<div style="margin-top:8px">
<button onclick=${() => this.emit("no")}>NO</button>
<button onclick=${() => this.emit("yes")}>YES</button>
</div>
`;
});
The component is shown below:
Slot
javascript
component("funny-button", () => {
return html`
<button
style="background: rgba(0, 0, 0, 0.4); color: #fff; padding: 10px 20px; font-size: 30px; border: 2px solid #fff; margin: 8px; transform: scale(0.9); box-shadow: 4px 4px rgba(0, 0, 0, 0.4); transition: transform 0.2s cubic-bezier(0.34, 1.65, 0.88, 0.925) 0s; outline: 0;"
>
<slot>
<span>No content found</span>
</slot>
</button>
`;
});
component("x-app", () => {
return html`
<funny-button></funny-button>
<funny-button>Click me!</funny-button>
`;
});