Skip to content

A QR Code for the current page

โ€ข ~2 min read

Extending Shoelace's QR Code component to show a QR Code for the current URL.

Iโ€™ve used the Shoelace QR Code component a few times and really like it. A common use-case Iโ€™ve had was basically just to show a QR Code for the current page to make it easy for people to quickly get to the URL, but I kinda thought that hard coding the value attribute to point to my prod URL was a little annoying since I had to know what that would be in advance, or risk forgetting to update it if I took a guess and then decided to change it.

Thatโ€™s when I had the idea to set it from the current location.href, which was nice but it still kinda bugged me that Iโ€™d need to write a little JS to target the element and update it.

Tonight I realized itโ€™d be pretty easy to just extend the Shoelace QR Code component to add this behavior in a way that already had access to the element.

<script type="module">
	import QrCode from "https://cdn.jsdelivr.net/npm/@shoelace-style/[email protected]/cdn/components/qr-code/qr-code.component.js";
	window.customElements.define(
		"href-qr-code",
		class HrefQrCode extends QrCode {
			connectedCallback() {
				super.connectedCallback();
				this.value =
					window.location.href;
			}
		},
	);
</script>

Thatโ€™s it! Now this just works:

<href-qr-code></href-qr-code>

Web components are dope.

Share this post

๐Ÿ“ง Email