Whether you're just getting started with web components or looking for easier ways (=less code, zero boilerplate, more features) to create them without the hassle of creating a class, a constructor, dealing with its inheritance chain, its various lifecycle methods and you'd rather want something that "just works", read on.
Inspired by the modern and more general concept of UI Components, we worked out a way to create them with a sigle function, taking the same simple form we are already accustomed to:
Please welcome this novel and experimental pattern, borrowed by the streams-oriented programming paradigm that enables you to create web components as if they were just "normal JS components".
import { rml, RegisterElement } from "rimmel";
RegisterElement('custom-element', ({ title }) => rml`
<h1>${title}</h1>
`);
Et voilà: you have your first functional web component, so you can use it alongside other frameworks, UI libraries, or even with vanilla JS applications. We'll better explain the word "functional" used here, lower down.
Async
Many things we do in web development are async.
Let's create a little example that fetches (async) the weather in San Francisco and shows it in your web component when data is available.
import { rml, RegisterElement } from "rimmel";
RegisterElement('custom-element', ({ title }) => {
const URL = 'https://api.open-meteo.com/v1/forecast'
+'?latitude=37.7749&longitude=-122.4194'
+'¤t_weather=true'
;
const weatherReport = fetch(URL)
.then(response => response.json())
.then(data => {
const temp = data.current_weather.temperature;
return `Temperature in San Francisco: ${temp}F`);
})
.catch(error => 'Error fetching weather data')
;
return rml`
<h1>${title}</h1>
<p>${weatherReport}</p>
`;
});
With Reactive Markup you can use promises directly in your templates; no need for any stitching or other patchwork. That contributes to keeping things lean and simple.
Reactivity
There's little point creating web components if they can't be reactive. Implementing that with vanilla JS is verbose, so let's use Reactive Markup conventions where all HTML attributes can be set to promises or observables.
Using these two primitives makes reactivity trivial, especially if your framework of choice has a good support for either.
Playground
Want to see this in action? Create your own reactive web components with ease? Jump on this Stackblitz and see what you can build. Observables work even better than promises!
Top comments (0)