Add Facebook Pixel Event Tracking in NextJS App Directory
Hadie Danker
Posted on June 17, 2023
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>
)
}
💖 💪 🙅 🚩
Hadie Danker
Posted on June 17, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.