Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active September 19, 2023 14:31
Show Gist options
  • Save WebReflection/043eae145ea539805b94da68b5ac2dad to your computer and use it in GitHub Desktop.
Save WebReflection/043eae145ea539805b94da68b5ac2dad to your computer and use it in GitHub Desktop.
Web Components, the React way, without Shadow DOM
// https://medium.com/@bdc/web-components-the-react-way-8ed5b6f4f942
const store = (() => {
let state;
return todos => {
if (todos) {
state = todos;
render("todo-list");
}
return state;
};
})();
const render = (component, parent = document.body) =>
parent.innerHTML = `<${component}></${component}>`;
customElements.define("todo-item", class extends HTMLElement {
static get observedAttributes() {
return ["index"];
}
attributeChangedCallback(name, old, change) {
this.index = change;
}
connectedCallback() {
this.innerHTML = `
<label>
<input type=checkbox>
${this.innerHTML}
</label>
`;
this.querySelector("input").addEventListener("click", () =>
store(store().filter((todo, index) => index != this.index)));
}
});
customElements.define("todo-list", class extends HTMLElement {
connectedCallback() {
this.innerHTML = `
<ul>
${store().map((todo, index) => `
<li>
<todo-item index=${index}>
${todo}
</todo-item>
</li>
`).join("")}
</ul>
`;
}
});
store(["Buy milk", "Call Sarah", "Pay bills"]);
@armujahid
Copy link

Thanks @WebReflection. I will definitely check heresy.

@mimiza
Copy link

mimiza commented Mar 23, 2021

Wow this is amazing. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment