Inspired upon a v0 implementation, I’ve recreated a Markdown renderer in Custom Elements v1. The result is <custom-markdown>
.
The code itself is pretty straightforward: other than some (contained) styling the custom element uses showdown to convert the Markdown to HTML. This conversion is triggered in the connectedCallback()
.
class Markdown extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({mode: 'closed'});
shadowRoot.innerHTML = `
<style>
:host { display: block; font-family: monospace; }
</style>
<div class="output"></div>
`;
this.output = shadowRoot.querySelector('.output');
this.converter = new showdown.Converter();
}
connectedCallback() {
this.output.innerHTML = this.converter.makeHtml(this.innerHTML);
}
};
customElements.define('custom-markdown', Markdown);
Here’s a working example (if your browser supports it):
See the Pen Custom Elements v1: Render Markdown with <custom-markdown> by Bramus (@bramus) on CodePen.
Related: Introducing Custom Elements →