Home > Software design >  How to know component is ready to render?
How to know component is ready to render?

Time:12-22

I am new in React-Native and I am stuck at one place to do in React-Native.

This is my one component :-

const ConentQR = (
  content: string,
  logo: Image.propTypes.source,
  logoSize: number,
) => {
  return (
    <QRCode
      color={Colors.DARK_PURPLE}
      content={content}
      codeStyle={'dot'}
      outerEyeStyle={'diamond'}
      logo={logo}
      logoSize={logoSize}
      backgroundColor={'transparent'}
    />
  );
};

The problem is I am facing in react native,This component (<QRCode) take some time to generate QR, so how I can put this block in any background thread so that I can show loader to user until it get prepared. I am getting stuck at this place and unable to resolve that for while. Please help anyone

CodePudding user response:

You could use the InteractionManager to schedule tasks in the background

import { InteractionManager } from 'react-native'

const ConentQR = (
  content: string,
  logo: Image.propTypes.source,
  logoSize: number,
) => {
  // Use a state variable to track the QR code
  const [qrCode, setQrCode] = useState(null)

  // Use the InteractionManager to run the generation process in the background
  InteractionManager.runAfterInteractions(() => {
    // Generate the QR code in the background
    const qrCode = generateQRCode(content, logo, logoSize)
    setQrCode(qrCode)
  })

  // Show a loading spinner while the QR code is generated 
  // so the user knows something is happening in the background
  if (!qrCode) {
    return <ActivityIndicator />
  }

  // Render the QR code when it's ready
  return <QRCode {...qrCode} />
}

I am using useState to keep track on the qr code and InteractionManager.runAfterInteractions to schedule the generation in the background. If the qr code is not ready it displays a loader. The generation happens in the generateQRCode() function.

  • Related