Skip to content

Instantly share code, notes, and snippets.

@muZk

muZk/Product.jsx

Created Oct 5, 2020
Embed
What would you like to do?
MercadoPago React
import React, { useEffect, useState } from 'react';
import { useParams } from "react-router-dom";
const FORM_ID = 'payment-form';
export default function Product() {
const { id } = useParams(); // id de producto
const [preferenceId, setPreferenceId] = useState(null);
useEffect(() => {
// luego de montarse el componente, le pedimos al backend el preferenceId
axios.post('/api/orders', { productId: id }).then((order) => {
setPreferenceId(order.preferenceId);
});
}, [id]);
useEffect(() => {
if (preferenceId) {
// con el preferenceId en mano, inyectamos el script de mercadoPago
const script = document.createElement('script');
script.type = 'text/javascript';
script.src =
'https://www.mercadopago.cl/integrations/v1/web-payment-checkout.js';
script.setAttribute('data-preference-id', preferenceId);
const form = document.getElementById(FORM_ID);
form.appendChild(script);
}
}, [preferenceId]);
return (
<form id={FORM_ID} method="GET" />
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment