QRCode.tsx 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. 'use client';
  2. import './style.scss';
  3. import { useEffect, useState } from 'react';
  4. import { QRCodeSVG } from 'qrcode.react';
  5. import { Button } from '@/components/ui/button';
  6. import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
  7. import { getDateFilename } from '@/lib/utils/client';
  8. type Props = {
  9. isEnable: boolean;
  10. open: boolean;
  11. onChange: (open: boolean) => void;
  12. }
  13. export default function QRCode({ isEnable, open, onChange }: Props) {
  14. const [url, setUrl] = useState<string>('');
  15. useEffect(() => {
  16. if (typeof window !== 'undefined') {
  17. setUrl(window.location.href);
  18. }
  19. }, []);
  20. if (!isEnable) {
  21. return;
  22. }
  23. const handleDownload = () => {
  24. const svgData = new XMLSerializer().serializeToString(
  25. document.getElementById('qrCode')!
  26. );
  27. const canvas = document.createElement('canvas');
  28. const ctx = canvas.getContext('2d')!;
  29. const img = new Image();
  30. img.onload = () => {
  31. canvas.width = img.width;
  32. canvas.height = img.height;
  33. ctx.drawImage(img, 0, 0);
  34. const pngFile = canvas.toDataURL('image/png');
  35. const link = document.createElement('a');
  36. link.download = getDateFilename('qr');
  37. link.href = pngFile;
  38. link.click();
  39. };
  40. img.src = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgData)));
  41. };
  42. return (
  43. <Dialog open={open} onOpenChange={onChange}>
  44. <DialogContent className='sm:max-w-md'>
  45. <DialogHeader>
  46. <DialogTitle>게시글 확인 QR</DialogTitle>
  47. <DialogDescription>
  48. 아래 QR을 스캔하여 게시글을 확인할 수 있습니다.
  49. </DialogDescription>
  50. </DialogHeader>
  51. <div className='flex items-center justify-center space-x-2'>
  52. <QRCodeSVG id='qrCode' value={url} />
  53. </div>
  54. <DialogFooter className='sm:justify-center'>
  55. <DialogClose asChild>
  56. <Button type='button' variant='outline' className='hover:bg-blue-500 hover:text-white sm:w-24' onClick={handleDownload}>
  57. 저장
  58. </Button>
  59. </DialogClose>
  60. </DialogFooter>
  61. </DialogContent>
  62. </Dialog>
  63. );
  64. }