Why you should
(and shouldn't)
use web components
name Jeremias Menichelli
from Argentina
now in Barcelona
work as a front end developer
twitter jeremenichelli
github jeremenichelli
They're not React components, that means they suck. End of the conversation.
Throw your React components away and #useThePlatform.
strong takes are
usually
WRONG
// <movie-box></movie-box>
class MovieBox extends HTMLElement {
constructor() {
super();
}
connectedCallback() { }
disconnectedCallback() { }
adoptedCallback() { }
attributeChangedCallback() { }
}
customElements.define('movie-box', MovieBox);
// <movie-box title="Batman Begins (2005)"></movie-box>
class MovieBox extends HTMLElement {
constructor() {
super();
this._root = this.attachShadow({ mode: 'closed' });
this._root.innerHTML = `
<style>
.title { background: #f9aaac; }
</style>
<h2 class="title">
${ this.getAttribute('title') }
</h2>
<slot></slot>
`;
}
}
const template = document.createElement('template');
template.innerHTML = `
<style>
.title { background: #f9aaac; }
</style>
<h2 class="title"></h2>
<slot></slot>
`;
class MovieBox extends HTMLElement {
constructor() {
super();
this._root = this.attachShadow({ mode: 'closed' });
this._root.appendChild(template.content.cloneNode(true));
}
}
// <movie-box title="Batman Begins (2005)"></movie-box>
class MovieBox extends HTMLElement {
connectedCallback() {
const title = this._root.querySelector('.title');
title.textContent = this.getAttribute('title');
}
}
static, no reactive
class MovieBox extends HTMLElement {
static get observedAttributes() {
return [ 'title' ];
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === 'title') {
const title = this._root.querySelector('.title');
title.textContent = this.getAttribute('title');
}
}
}
// const movie = document.createElement('movie-box');
// movie.title = "Batman Begins (2005)"
class MovieBox extends HTMLElement {
set title(value) {
const title = this._root.querySelector('.title');
title.textContent = value;
}
}
developer experience
"Unfortunately the developer experience of building an application with web components today is quite painful"
Sam Saccone, Developer Advocate at Google
Developer experience can be solved by us
import collectRefs from 'web-component-refs';
const template = document.createElement('template');
template.innerHTML = `
<h2 class="title" ref="title"></h2>
`;
class MovieBox extends HTMLElement {
connectedCallback() {
collectRefs();
// this.refs.title -> <h2 class="title"></h2>
}
}
web components
solution for DOM manipulation
solution for data management
solution for elements definition
polyfill
framework
WHEN?
web components are not here to wipe frameworks out, they are here to empower them.