React Segment Analytics
React integration for Segment Analytics
Install
-
npm install react-segment-analytics
or yarn add react-segment-analytics
Use
import { render } from 'react-dom';
import Segment from 'react-segment-analytics';
import { App } from './components';
render(
<Segment writeKey="my-write-key">
<App />
</Segment>,
document.getElementById('root'),
);
Exports
Segment
import Segment from 'react-segment-analytics';
Props
You can pass any of the Segment Analytics browser settings or init options to
the Segment
component. The only required prop is writeKey
.
traits
Type: Traits
(optional)
The traits
prop defines traits associated with the user during identification.
Be sure to provide the id
trait to make the user onymous.
import type { Traits } from 'react-segment-analytics';
Hooks
useSegmentPage
import { useEffect } from 'react';
import { useSegmentPage } from 'react-segment-analytics';
function Home() {
const page = useSegmentPage();
useEffect(() => {
page('Home');
}, [page]);
return (
<main>
<h1>Home</h1>
{/* ... */}
</main>
);
}
The useSegmentPage
hook returns a function that, when called, denotes a page
change event. The page
function accepts an optional page category (string
),
optional page name (string
), and optional page properties
(Record<string, unknown>
) as its first, second, and third parameters
respectively. The page function returns a Promise that monitors the network
request to Segment.
useSegmentTrack
import { useSegmentTrack } from 'react-segment-analytics';
function MyButton() {
const track = useSegmentTrack();
const handleClick = () => {
track('Button click');
};
return <button onClick={handleClick}>Click me</button>;
}
The useSegmentTrack
hook returns a function that, when called, emits an event
to Segment. The track function accepts a required event name (string
) and
optional event properties (Record<string, unknown>
) as its first and second
parameters respectively. The track function returns a Promise that monitors the
the network request to Segment.
Contributing
To contribute, clone this repository, then run the following commands:
yarn set version latest
yarn up "*" "@*/*"
- If you use VIM, run
yarn sdks vim
. - If you use Visual Studio Code, run
yarn sdks vscode
.