This morning, I needed to add QR Codes to my app. After some research, I have decided to use the popular qrcode - npm (npmjs.com), which currently has over 2 million weekly downloads.
Adding it to my Sveltekit project was very easy:
npm i qrcode
npm i --save-dev @types/qrcode
The SVG output feature is particularly useful because I need to display the QR code at different resolutions for both screen and print.
I always create a component to wrap libraries, such as qrcode, in case I need to change it for a different library later. Svelte makes this easy.
<script lang="ts">
import { Spinner } from "flowbite-svelte";
import { createEventDispatcher } from "svelte";
import QRCode from "qrcode";
export let code: string;
let qrCode: string | undefined;
let error: string | undefined;
const dispatch = createEventDispatcher<{ error: string }>();
$: {
generateQRCode(code);
}
async function generateQRCode(code: string) {
try {
qrCode = await QRCode.toString(code, { type: "svg" });
} catch (err) {
const qrCodeError = (err as Error).message || "Unknown error: Unable to render QR Code.";
if (error) {
dispatch("error", qrCodeError);
}
}
}
</script>
{#if !error}
{#if qrCode}
<div class="w-64">
{@html qrCode}
</div>
{:else}
<div class="w-64 h-64">
<Spinner />
</div>
{/if}
{:else}
<p>Unable to render QR Code.</p>
{/if}
The component must report any errors and display a generic error message if one occurs. It also uses the reactive nature of Svelte to update the QRCode if it changes in its parent.
This new component meets all my app requirements for adding QR codes.