-
Notifications
You must be signed in to change notification settings - Fork 18
Using Bricks with Next.js
Francine Emilia Costa edited this page Aug 23, 2023
·
3 revisions
Next.js is a framework for creating interfaces with React components. Given this, it is possible to use our React SDK to integrate Bricks - as well as other solutions provided through the React SDK.
However, our SDK was structured for Client Side Rendering while Next.js works by default with Server Side Rendering. So, when using our SDK, you need to take this into account. It is possible to perform this integration using dynamic import - as indicated in the Next.js documentation.
Below you will find an example of dynamic import code of a component available in our SDK - the Payment Brick.
index.tsx
Example
import Head from "next/head";
import styles from "../styles/Home.module.css";
import dynamic from "next/dynamic";
const CheckoutMercadoPago = dynamic(() => import("./checkoutMercadoPago"), {
ssr: false,
});
export default function Home() {
return (
<>
<Head>
<title>Checkout Brick + NextJS</title>
<meta name="description" content="Generated by create next app" />
</Head>
<main className={styles.main}>
<CheckoutMercadoPago />
</main>
</>
);
}
checkoutMercadoPago.tsx
Example
import { initMercadoPago, Payment } from "@mercadopago/sdk-react";
initMercadoPago("<YOUR_PUBLIC_KEY>");
const CheckoutMercadoPago = () => {
const initialization = {
amount: <YOUR_AMOUNT>,
preferenceId: "<YOUR_PREFERENCE_ID>"
};
const customization = {
paymentMethods: {
ticket: "all",
bankTransfer: "all",
creditCard: "all",
debitCard: "all",
mercadoPago: "all",
},
};
const onSubmit = async ({ selectedPaymentMethod, formData }) => {
// callback called when the submit button is pressed
return new Promise((resolve, reject) => {
fetch("/process_payment", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(formData),
})
.then((response) => response.json())
.then((response) => {
// receive the payment response
resolve();
})
.catch((error) => {
// deal with erros in the payment creation proccess
reject();
});
});
};
const onError = async (error) => {
// callback to error with Bricks
console.log(error);
};
const onReady = async () => {
// callback executed when Brick is loaded
};
return (
<Payment
initialization={initialization}
customization={customization}
onSubmit={onSubmit}
onReady={onReady}
onError={onError}
/>
);
};
export default CheckoutMercadoPago;