Skip to content

Latest commit

 

History

History

Folders and files

README.md

X Pixel with React

This sample shows how to add the X Pixel to a React single-page app built with Vite and React Router. The X conversion tracking base code is in the <head> of index.html. The useXPixelPageViews hook in src/x-pixel.ts sends a page view on every client-side navigation, and the Buy button on the home page sends a purchase event with sendXEvent.

How to use

Install the dependencies:

npm install

Copy the .env.local.example file to .env.local (which will be ignored by Git):

cp .env.local.example .env.local

Set VITE_X_PIXEL_ID to your pixel ID from X Ads Events Manager. To send the purchase event, create an event in Events Manager and set VITE_X_PURCHASE_EVENT_ID to its event ID (it looks like tw-abc12-def34). Each event you create has its own ID.

Start the development server:

npm run dev

How page views are counted

The base code's twq('config', …) call sends a page view for the page the app loads on. React Router changes pages without reloading, so useXPixelPageViews calls twq('config', …) again each time the pathname changes. It skips the first page, so that page is not counted twice.