Rendering Markdown using Custom Elements v1

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.

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Unless noted otherwise, the contents of this post are licensed under the Creative Commons Attribution 4.0 License and code samples are licensed under the MIT License

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.