Facebook Pixel is a powerful tool that allows you to track and optimize conversions from Facebook ads, build custom audiences, and measure the effectiveness of your marketing campaigns.
And this how to itegrate facebook pixel with easy with react-facebook-pixel
Create component in directory component (for example)
src/components/pixel-events.tsx
"use client";
import React, { useEffect } from "react";
import { usePathname, useSearchParams } from "next/navigation";
export const FacebookPixelEvents: React.FC = () => {
const pathname = usePathname();
const searchParams = useSearchParams();
useEffect(() => {
import("react-facebook-pixel")
.then((x) => x.default)
.then((ReactPixel) => {
ReactPixel.init("FACEBOOK_PIXEL_ID"); //don't forget to change this
ReactPixel.pageView();
});
}, [pathname, searchParams]);
return null;
};
And then can be imported into a layout.
import { Suspense } from 'react'
import { FacebookPixelEvents } from '../components/pixel-events'
export default function Layout({ children }) {
return (
<html lang="en">
<body>
{children}
<Suspense fallback={null}>
<FacebookPixelEvents />
</Suspense>
</body>
</html>
)
}
Top comments (2)
How can we track custom events in this?
I discovered a solution:
Create a function in the same file as the code above, then import and run it where you want.
export const nameEvent = async () => {
const { default: ReactPixel } = await import("react-facebook-pixel");
ReactPixel.init("Your Pixel ID");
ReactPixel.track("Name", { data });
};