Skip to content

Instantly share code, notes, and snippets.

@NicolasLopes7
Created January 11, 2022 04:34
Show Gist options
  • Save NicolasLopes7/e39d902bee9e53cd72115ac370e658ae to your computer and use it in GitHub Desktop.
Save NicolasLopes7/e39d902bee9e53cd72115ac370e658ae to your computer and use it in GitHub Desktop.

useScript hook:

import { useState, useEffect } from 'react';

export default function useScript(url, name) {
  const [lib, setLib] = useState({});

  useEffect(() => {
    const script = document.createElement('script');

    script.src = url;
    script.async = true;
    script.onload = () => setLib({ [name]: window[name] });

    document.body.appendChild(script);

    return () => {
      document.body.removeChild(script);
    };
  }, [url]);

  return lib;
}

implementation:

  const [client, setClient] = useState(null);
  const { MercadoPago } = useScript(
    'https://sdk.mercadopago.com/js/v2',
    'MercadoPago'
  );

  useEffect(() => {
    if (MercadoPago) {
      setClient(
        new MercadoPago('your_key', {
          locale: 'pt-BR',
        })
      );
    }
  }, [MercadoPago]);

  function handlePayment() {
      client.checkout({
        preference: {
          id: 'your_preference_id',
        },
        render: {
          container: '.cho-container',
          label: 'Pagar',
        },
        autoOpen: true,
      });
    }
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment