Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add facebook Pixel on Next.js react app?

I know this may be a dumb question. How can I do to use facebook pixel on a next.js react app ?

like image 542
Henimbola Tsihala Andrianatoan Avatar asked Nov 11 '20 18:11

Henimbola Tsihala Andrianatoan


People also ask

Does Facebook use next js?

What Is It: Next. js is an open-source front end web development JavaScript framework based on the popular Facebook-backed React.

Can you add next js to an existing react app?

js provides a zero-configuration setup process similar to what Create React App does through a package called Create Next App. Today, we will look at how you can make use of Next. js on a pre-existing React application. This will allow you to add SSR to an existing project.


2 Answers

there are no dumb questions.

You can see nextjs example about how implements fb pixel. Nextjs Facebook Pixel

like image 152
Nico Avatar answered Sep 19 '22 15:09

Nico


Solution with typescript and hook with NextJs

  1. Install react-facebook-pixel yarn add react-facebook-pixel
  2. In your file _app.tsx
// pages/_app.tsx

import { useEffect } from 'react'
import { useRouter } from 'next/router'

const App = ({ Component, pageProps }) => {
  const router = useRouter()

  useEffect(() => {
    import('react-facebook-pixel')
      .then((x) => x.default)
      .then((ReactPixel) => {
        ReactPixel.init('XXXXXXXXXXXXXXXXXXXXX') // facebookPixelId
        ReactPixel.pageView()

        router.events.on('routeChangeComplete', () => {
          ReactPixel.pageView()
        })
      })
  }, [router.events])

  

  return <Component {...pageProps} />
}

export default App

Remark: it works with typescript or JavaScript

like image 30
Alan Avatar answered Sep 18 '22 15:09

Alan