snort/src/Element/QrCode.tsx

52 lines
1.5 KiB
TypeScript
Raw Normal View History

2023-01-07 20:54:12 +00:00
import QRCodeStyling from "qr-code-styling";
2023-01-08 20:36:36 +00:00
import { useEffect, useRef } from "react";
2023-01-07 20:54:12 +00:00
2023-01-16 17:48:25 +00:00
export interface QrCodeProps {
data?: string,
link?: string,
avatar?: string,
height?: number,
2023-01-29 12:19:53 +00:00
width?: number,
className?: string
2023-01-16 17:48:25 +00:00
}
export default function QrCode(props: QrCodeProps) {
const qrRef = useRef<HTMLDivElement>(null);
2023-01-08 20:36:36 +00:00
2023-01-07 20:54:12 +00:00
useEffect(() => {
2023-01-16 17:48:25 +00:00
if ((props.data?.length ?? 0) > 0 && qrRef.current) {
2023-01-07 20:54:12 +00:00
let qr = new QRCodeStyling({
width: props.width || 256,
height: props.height || 256,
2023-01-08 20:36:36 +00:00
data: props.data,
2023-01-07 20:54:12 +00:00
margin: 5,
type: 'canvas',
image: props.avatar,
dotsOptions: {
type: 'rounded'
},
cornersSquareOptions: {
type: 'extra-rounded'
2023-01-29 14:55:51 +00:00
},
imageOptions: {
crossOrigin: "anonymous"
2023-01-07 20:54:12 +00:00
}
});
qrRef.current.innerHTML = "";
qr.append(qrRef.current);
2023-01-08 20:36:36 +00:00
if (props.link) {
qrRef.current.onclick = function (e) {
let elm = document.createElement("a");
2023-01-16 17:48:25 +00:00
elm.href = props.link!;
2023-01-08 20:36:36 +00:00
elm.click();
}
2023-01-07 20:54:12 +00:00
}
2023-01-16 17:48:25 +00:00
} else if (qrRef.current) {
2023-01-07 23:01:32 +00:00
qrRef.current.innerHTML = "";
2023-01-07 20:54:12 +00:00
}
2023-01-08 20:36:36 +00:00
}, [props.data, props.link]);
2023-01-07 20:54:12 +00:00
return (
2023-01-29 12:19:53 +00:00
<div className={`qr${props.className ? ` ${props.className}` : ""}`} ref={qrRef}></div>
2023-01-07 20:54:12 +00:00
);
}