To integrate Preo Widget with Next.js, you'll need to add the Preo JavaScript SDK and configure your application to handle web components properly.
App Router (Next.js 13+)
For Next.js applications using the App Router, create a client component wrapper:
- Create a new file
app/components/PreoWidget.tsx:
'use client';
import { useEffect } from 'react';
declare global {
namespace JSX {
interface IntrinsicElements {
'preo-storefront': React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement> & {
'sdk-id': string;
}, HTMLElement>;
}
}
}
export default function PreoWidget({ sdkId }: { sdkId: string }) {
useEffect(() => {
// Load the Preo SDK script
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/@preo-live/[email protected]/dist/components.umd.js';
script.async = true;
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
};
}, []);
return <preo-storefront sdk-id={sdkId}></preo-storefront>;
}
- Use the component in your pages:
import PreoWidget from '@/components/PreoWidget';
export default function HomePage() {
return (
<div>
<h1>Welcome to our store</h1>
<PreoWidget sdkId="your-sdk-id-here" />
</div>
);
}
Pages Router (Legacy)
For Next.js applications using the Pages Router:
- Add the Preo SDK script to your
_document.tsx or _document.js:
import { Html, Head, Main, NextScript } from 'next/document';
export default function Document() {
return (
<Html>
<Head>
<script
src="https://cdn.jsdelivr.net/npm/@preo-live/[email protected]/dist/components.umd.js"
async
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
- Create a component wrapper to handle the web component:
import { useEffect, useRef } from 'react';
export default function PreoWidget({ sdkId }) {
const containerRef = useRef(null);
useEffect(() => {
// Ensure the web component is defined before rendering
if (typeof window !== 'undefined' && containerRef.current) {
containerRef.current.innerHTML = `<preo-storefront sdk-id="${sdkId}"></preo-storefront>`;
}
}, [sdkId]);
return <div ref={containerRef} />;
}
Dynamic Import (Alternative)
For better performance and code splitting, you can dynamically import the Preo SDK:
import dynamic from 'next/dynamic';
const PreoWidget = dynamic(() => import('./PreoWidget'), {
ssr: false,
loading: () => <p>Loading storefront...</p>
});
export default function Page() {
return <PreoWidget sdkId="your-sdk-id-here" />;
}
With these configurations, you can now use the Preo widget throughout your Next.js application.
Last modified on