React QR Code Integration

Build QR code components for React applications with hooks and best practices.

QR Code Component

A simple, reusable QR code component for React:

QRCode.jsx
import { useState, useEffect } from 'react';

export function QRCode({ data, size = 200, className }) {
  const [imageUrl, setImageUrl] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const generateQR = async () => {
      setLoading(true);
      try {
        const response = await fetch('https://www.qrcodeapi.io/api/generate', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${import.meta.env.VITE_QR_API_KEY}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ data, size, format: 'png' })
        });
        
        const blob = await response.blob();
        setImageUrl(URL.createObjectURL(blob));
      } finally {
        setLoading(false);
      }
    };
    
    if (data) generateQR();
  }, [data, size]);

  if (loading) return <div className={className}>Loading...</div>;
  
  return <img src={imageUrl} alt="QR Code" className={className} />;
}

Custom Hook

useQRCode.js
import { useState, useEffect, useCallback } from 'react';

export function useQRCode(data, options = {}) {
  const [qrUrl, setQrUrl] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const generate = useCallback(async () => {
    if (!data) return;
    
    setLoading(true);
    setError(null);

    try {
      const response = await fetch('https://www.qrcodeapi.io/api/generate', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${import.meta.env.VITE_QR_API_KEY}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          data,
          size: options.size || 200,
          format: options.format || 'png'
        })
      });

      if (!response.ok) throw new Error('Generation failed');

      const blob = await response.blob();
      setQrUrl(URL.createObjectURL(blob));
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }, [data, options.size, options.format]);

  useEffect(() => { generate(); }, [generate]);

  return { qrUrl, loading, error, regenerate: generate };
}

Usage Example

App.jsx
import { QRCode } from './QRCode';
import { useQRCode } from './useQRCode';

function App() {
  // Using the component
  return (
    <div>
      <QRCode data="https://example.com" size={300} />
    </div>
  );
}

// Or using the hook for more control
function QRGenerator() {
  const { qrUrl, loading, error } = useQRCode('https://example.com');

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error}</p>;

  return <img src={qrUrl} alt="QR Code" />;
}

Ready to Build with React?

Get your free API key and start building QR code components.

Get Your Free API Key