kozakdenys/qr-code-styling

Nextjs Only 1 Instance problem

Jervx opened this issue · 3 comments

I have this code, then I called it 2x somewhere

"use client"
import React, { useEffect, useRef } from "react";
import QRCodeStyling from "qr-code-styling";

import { cn } from "@/lib/utils";

type Props = {
    className?: string;
    value: string;
};

const qrCode = new QRCodeStyling({
    width: 260,
    height: 260,
    type: "svg",
    backgroundOptions : {
        color : "transparent"
    }, 
    dotsOptions: {
        color: "#4267b2",
        type: "rounded",
    },
});

const QRCode = ({ className, value }: Props) => {
    const ref = useRef<HTMLDivElement>(null);

    useEffect(()=>{
        if (!ref || !ref.current) return;
        qrCode.update({
            data: value
          });
    },[value])

    useEffect(() => {
        if (!ref || !ref.current) return;
        qrCode.append(ref.current);
    }, []);

    return (
        <div className={cn("rounded-xl overflow-clip", className)} ref={ref} />
    );
};

export default QRCode;

I called it 2x here

           <div> 
                <QRCode value={'yes'}/>
                <QRCode value={'a different one'}/>
            </div>

it only shows the last one
image

when I removed the last <QRCode value={'a different one'}/> this is the result

image

How can I prevent this from happening?

I also tried it on the sample code which is also happens thesame

image

I have the same issue. No solution found yet

I found a way to deal with it. Instead of svg, we'll use canvas. By some chance the library can't separate the different information for each svg, so they'll have the same value, and by switching to rendering with canvas we won't have this problem. In addition, I've also allocated to instantiate the qrcode class inside the component function, thus creating a separate instance for each qrcode, avoiding replicating the qrcode values. My code below:

src/app/page.tsx

"use client";

import * as S from './styles';
import QRCodeStyling from 'qr-code-styling';

interface Props {
  value: string;
}

const QRCode = ({ value }: Props) => {
  const qrCode = new QRCodeStyling({
    width: 500,
    height: 500,
    type: 'canvas',
    backgroundOptions: {
      color: 'transparent',
    },
    dotsOptions: {
      color: '#4267b2',
      type: 'rounded',
    },
    data: value,
  });

  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!ref || !ref.current) return;
    qrCode.update({
      data: value,
    });
  }, [value]);

  useEffect(() => {
    if (!ref || !ref.current) return;
    qrCode.append(ref.current);
  }, []);

  return <S.Qrcode ref={ref} />;
}; 

export default function Page() {
  return (
    <S.Container>
      hi
      <QRCode value={'01011010100101'} />
      other
      <QRCode value={'awdawddawdawd'} />
    </S.Container>
  );
};

image