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,
});
}
}