• Stars
    star
    160
  • Rank 226,515 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 5 years ago
  • Updated 12 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

[DEPRECATED AND UNSUPPORTED] The hassle-free way to integrate analytics into your React application.

Segment React Quickstart Guide

You can't fix what you can't measure

Analytics helps you measure your users, product, and business. It unlocks insights into your app's funnel, core business metrics, and whether you have product-market fit.

How to get started

  1. Collect analytics data from your app(s).
    • The top 200 Segment companies collect data from 5+ source types (web, mobile, server, CRM, etc.).
  2. Send the data to analytics tools (for example, Google Analytics, Amplitude, Mixpanel).
    • Over 250+ Segment companies send data to eight categories of destinations such as analytics tools, warehouses, email marketing and remarketing systems, session recording, and more.
  3. Explore your data by creating metrics (for example, new signups, retention cohorts, and revenue generation).
    • The best Segment companies use retention cohorts to measure product market fit. Netflix has 70% paid retention after 12 months, 30% after 7 years.

Segment collects analytics data and allows you to send it to more than 250 apps (such as Google Analytics, Mixpanel, Optimizely, Facebook Ads, Slack, Sentry) just by flipping a switch. You only need one Segment code snippet, and you can turn integrations on and off at will, with no additional code. Sign up with Segment today.

Why?

  1. Power all your analytics apps with the same data. Instead of writing code to integrate all of your tools individually, send data to Segment, once.

  2. Install tracking for the last time. We're the last integration you'll ever need to write. You only need to instrument Segment once. Reduce all of your tracking code and advertising tags into a single set of API calls.

  3. Send data from anywhere. Send Segment data from any device, and we'll transform and send it on to any tool.

  4. Query your data in SQL. Slice, dice, and analyze your data in detail with Segment SQL. We'll transform and load your customer behavioral data directly from your apps into Amazon Redshift, Google BigQuery, or Postgres. Save weeks of engineering time by not having to invent your own data warehouse and ETL pipeline.

    For example, you can capture data on any app:

    analytics.track('Order Completed', { price: 99.84 })

    Then, query the resulting data in SQL:

    select * from app.order_completed
    order by price desc

๐Ÿš€ Startup Program

If you are part of a new startup (<$5M raised, <2 years since founding), we just launched a new startup program for you. You can get a Segment Team plan (up to $25,000 value in Segment credits) for free up to 2 years โ€” apply here!

๐Ÿƒ๐Ÿ’จ Quickstart

In this tutorial you'll add your write key to this React demo app to start sending data from the app to Segment, and from there to any of our destinations, using our Analytics.js library. Once your app is set up, you'll be able to turn on new destinations with the click of a button! Ready to try it for yourself? Scroll down to the demo section and run the app!

Start sending data from any source and see events live in the Segment debugger:


Once you have data being sent to Segment, forward this data to any of our 250+ destinations:

๐Ÿ”Œ Installing on Your App

How do you get this in your own React app? Follow the steps below.

โœ‚๏ธ Step 1: Copy the Snippet

To install Segment in your own app first sign up with Segment and locate your Segment project's Write Key. Then, copy and paste the snippet below into the head tag of your site. Replace YOUR_WRITE_KEY in the snippet below with your Segment project's write key.

Tip! You can find your write key in your Segment project setup guide or settings.

<script type="text/javascript">
  !function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","debug","page","once","off","on"];analytics.factory=function(t){return function(){var e=Array.prototype.slice.call(arguments);e.unshift(t);analytics.push(e);return analytics}};for(var t=0;t<analytics.methods.length;t++){var e=analytics.methods[t];analytics[e]=analytics.factory(e)}analytics.load=function(t,e){var n=document.createElement("script");n.type="text/javascript";n.async=!0;n.src="https://cdn.segment.com/analytics.js/v1/"+t+"/analytics.min.js";var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(n,a);analytics._loadOptions=e};analytics.SNIPPET_VERSION="4.1.0";
  analytics.load("YOUR_WRITE_KEY");
  // analytics.page() // Uncomment if your application is NOT an SPA
  }}();
</script>

Now window.analytics is loaded and available to use throughout your app!

Note: If you are seeing compilation errors, you may need to declare the windows interface as a global:

declare global {
  interface Window { analytics: any; }
}

In the next sections you'll build out your implementation to track page loads, to identify individual users of your app, and track the actions they take.

๐Ÿ“ฑ Step 2: Track Page Views in an SPA

Tip! If your React application is not a Single Page application, you can uncomment the section in the above snippet and skip to Step 3.

The snippet from Step 1 loads Analytics.js into your app and is ready to track page loads. However, most React apps are a Single Page App (SPA), and in SPAs clicking a link or a new tab does not reload the whole webpage.

The page method lets you record page views on your website, along with optional information about the page being viewed. You can read more about how this works in the page reference.

This means that using analytics.page() in index.html on a SPA will not detect page component loads, and you'll need to simulate a page load some other way. You can use react-router and React's lifecycle methods to create page calls.

If you separate your pages into their own components and allow the <Route /> component to handle when the page renders, you can use componentDidMount to invoke page calls. The example below shows one way you could do this.

export default class HomePage extends Component {
  componentDidMount() {
    window.analytics.page('Home');
  }

  render() {
    return (
      <h1>
        Home page.
      </h1>
    );
  }
}

๐Ÿ” Step 3: Identify Users

The identify method is how you tell Segment who the current user is. It includes a unique User ID and any optional traits you can pass on about them. You can read more about this in the identify reference.

Note: You don't need to call identify for anonymous visitors to your site. Segment automatically assigns them an anonymousId, so just calling page and track still works just fine without identify.

Here's what a basic call to identify might look like:

window.analytics.identify('f4ca124298', {
  name: 'Michael Bolton',
  email: '[email protected]'
});

This call identifies Michael by his unique User ID and labels him with name and email traits.

In React, if you have a form where users sign up or log in, you can use the onSubmit handler to call identify, as in the example below:

export default class IdentifyForm extends Component {
  state = {
    name: '',
    email: ''
  };

  handleChange(event) {
    this.setState({ value: event.target.value });
  }

  handleSubmit() {
    const { name, email } = this.state;

    // Add your own unique ID here or we will automatically assign an anonymousID
    window.analytics.identify({
      name,
      email
    });
  }

  render() {
    const { name, email } = this.state;

    return (
      <form onSubmit={this.handleSubmit}>
        <input name="name" type="text" value={name} onChange={this.handleChange} />
        <input name="email" type="email" value={email} onChange={this.handleChange} />
        <input type="submit" value="Submit" />
      </form>
    );
 }
}

Tip! Other handlers might be better for other situations. You can see the React docs on event handlers for more information.

โฐ Step 4: Track Actions

The track method is how you tell Segment about which actions your users are performing on your site. Every action triggers what we call an "event", which can also have associated properties. It is important to figure out exactly what events you want to track instead of tracking anything and everything. A good way to do this is to build a tracking plan. You can read more about track in the track reference.

Here's what a call to track might look like when a user bookmarks an article:

window.analytics.track('Article Bookmarked', {
  title: 'Snow Fall',
  subtitle: 'The Avalanche at Tunnel Creek',
  author: 'John Branch'
});

The snippet tells us that the user just triggered the Article Bookmarked event, and the article they bookmarked was the Snow Fall article authored by John Branch. Properties can be anything you want to associate to an event when it is tracked.

Track Calls with Event Handlers

In React, you can use several event handlers, such as onClick, onSubmit, onMouseOver, to call the track events. In the example below, we use the onClick handler to make a track call to log a User Signup.

export default class SignupButton extends Component {
  trackEvent() {
    window.analytics.track('User Signup');
  }

  render() {
    return (
      <button onClick={this.trackEvent}>
        Signup with Segment today!
      </button>
    );
  }
}

Tip! Other handlers might be better for other situations. You can see the React docs on event handlers for more information.

Track Calls with Lifecycle Methods

Lifecycle methods are also great for tracking particular events, and in fact we used a lifecycle method in Step 2 to track page component loads. For example, if you want to track components that are conditionally rendered from a parent component and that are outside the scope of a page call, then you can use componentDidMount to trigger a track event:

export default class VideoPlayer extends Component {
  componentDidMount() {
    window.analytics.track('Video Played');
  }

  render() {
    return (
      <video autoplay>
        <source src="https://www.youtube.com/watch?v=dQw4w9WgXcQ" type="video/youtube">
      </video>
    );
  }
}

๐Ÿค” What's next?

Once you've added a few track calls, you're done! You've successfully installed Analytics.js tracking. Now you're ready to see your data in the Segment dashboard, and turn on any destination tools. ๐ŸŽ‰

๐ŸŽ“ Advanced

Once you've mastered the basics, here are some advanced use cases you can apply with Segment.

Track Calls for Error Logging

You can also use track calls to log errors, using a higher-order component such as ErrorBoundary to wrap around child components. Then, when an error occurs you log the error with track and gracefully display the appropriate child component. In this example, when an error is caught by componentDidCatch, we set the state, track the error, and then the ErrorComponent will be rendered.

export default class ErrorBoundary extends Component {
  static propTypes = {
    /**
     * Fallback component to display when uncaught exceptions occur in a component tree:
     * function({ error: PropTypes.object, errorInfo: PropTypes.object }): PropTypes.node
     */
    errorComponent: PropTypes.func
  };

  static defaultProps = {
    errorComponent: () => null
  };

  state = {
    error: null,
    errorInfo: null
  };

  componentDidCatch(error, errorInfo) {
    const { error, errorInfo } = this.state;

    this.setState({
      error,
      errorInfo
    });

    window.analytics.track('JavaScript Error', {
      error,
      errorInfo
    });
  }

  render() {
    const { error, errorInfo } = this.state;
    const { errorComponent: ErrorComponent, children } = this.props;

    return error ? (
      <ErrorComponent
        error={error}
        errorInfo={errorInfo}
      />
    ) : (
      children
    );
  }
}

Typechecking with PropTypes

You can use typechecking with prop-types to catch a lot of potential bugs and prevent handing down information in the wrong format. For example, you can enforce a format for user related objects which can help with data standardization. You can get creative with the traits you expect to be sent to Segment for identify and track:

export default class User extends Component {
  static propTypes = {
    id: PropTypes.string,
    identifyTraits: PropTypes.shape({
      name: PropTypes.string.isRequired,
      email: PropTypes.string.isRequired,
      isAuthorized: PropTypes.bool.isRequired
    }),
    trackTitle: PropTypes.string,
    trackTraits: PropTypes.object
  };

  identify() {
    const { id, identifyTraits } = this.props;

    window.analytics.identify(id, identifyTraits);
  }

  track() {
    const { trackTitle, trackTraits } = this.props;

    window.analytics.track(trackTitle, trackTraits);
  }

  render() {
    const { children } = this.props;

    return children;
  }
}

If you love typechecking, you'll love our open-source project typewriter, which enforces a strongly-typed tracking spec via a JSON schema. Interested more in data standardization? Check out our protocols product to improve data quality.

You may wondering what you can be doing with all the raw data you are sending to Segment from your React app. With our warehouses product, your analysts and data engineers can shift focus from data normalization and pipeline maintenance to providing insights for business teams. Having the ability to query data directly in SQL and layer on visualization tools can take your product to the next level.

๐Ÿ’พ Warehouses

A warehouse is a special subset of destinations where we load data in bulk at a regular intervals, inserting and updating events and objects while automatically adjusting their schema to fit the data you've sent to Segment. We do the heavy lifting of capturing, schematizing, and loading your user data into your data warehouse of choice.

Examples of data warehouses include Amazon Redshift, Google BigQuery, MySQL, and Postgres.

๐Ÿ“บ Demo

To start with this demo app, follow the instructions below:

  1. Sign up with Segment and edit the snippet in index.html to replace YOUR_WRITE_KEY with your Segment Write Key.

    Tip! You can find your key in your project setup guide or settings in the Segment.

    Your snippet will look something like the example below.

    <script type="text/javascript">
      !function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","debug","page","once","off","on"];analytics.factory=function(t){return function(){var e=Array.prototype.slice.call(arguments);e.unshift(t);analytics.push(e);return analytics}};for(var t=0;t<analytics.methods.length;t++){var e=analytics.methods[t];analytics[e]=analytics.factory(e)}analytics.load=function(t,e){var n=document.createElement("script");n.type="text/javascript";n.async=!0;n.src="https://cdn.segment.com/analytics.js/v1/"+t+"/analytics.min.js";var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(n,a);analytics._loadOptions=e};analytics.SNIPPET_VERSION="4.1.0";
      analytics.load("YOUR_WRITE_KEY");
      }}();
    </script>
  2. From the command line, use npm install to install the dependencies, then npm start to run the app.

    npm install
    npm start
  3. Go to the Segment site, and in the Debugger look at the live events being triggered in your app. You should see the following:

    • Page event: Home - When someone views the home page.
    • Page event: About - When someone views the about page.
    • Track event: Learn React Link Clicked - When someone clicks the "Learn React" link.

Congrats! You're seeing live data from your demo React app in Segment! ๐ŸŽ‰

๐Ÿ”’ What about privacy?

Want to allow your visitors to control and customize their tracking preferences on your site? Integrate our consent-manager, which is imported via the snippet and uses our pre-built React component under the hood.

๐Ÿ“ Docs & Feedback

Check out our full Analytics.js reference to see what else is possible, or read about the Tracking API methods to get a sense for the bigger picture. If you have any questions, or see anywhere we can improve our documentation, let us know!

More Repositories

1

evergreen

๐ŸŒฒ Evergreen React UI Framework by Segment
JavaScript
12,161
star
2

kafka-go

Kafka library in Go
Go
7,073
star
3

analytics.js

The hassle-free way to integrate analytics into any web application.
JavaScript
4,775
star
4

myth

A CSS preprocessor that acts like a polyfill for future versions of the spec.
JavaScript
4,345
star
5

ksuid

K-Sortable Globally Unique IDs
Go
4,121
star
6

daydream

A chrome extension to record your actions into a nightmare or puppeteer script
JavaScript
2,768
star
7

chamber

CLI for managing secrets
Go
2,283
star
8

stack

A set of Terraform modules for configuring production infrastructure with AWS
HCL
2,098
star
9

ui-box

Blazing Fast React UI Primitive
TypeScript
1,052
star
10

encoding

Go package containing implementations of efficient encoding, decoding, and validation APIs.
Go
911
star
11

golines

A golang formatter that fixes long lines
Go
803
star
12

asm

Go library providing algorithms optimized to leverage the characteristics of modern CPUs
Go
795
star
13

analytics-node

The hassle-free way to integrate analytics into any node application.
JavaScript
593
star
14

topicctl

Tool for declarative management of Kafka topics
Go
558
star
15

aws-okta

aws-vault like tool for Okta authentication
Go
541
star
16

niffy

Perceptual diffing suite built on Nightmare
JavaScript
535
star
17

analytics-ios

The hassle-free way to integrate analytics into any iOS application.
Objective-C
388
star
18

analytics-ruby

The hassle-free way to integrate analytics into any Ruby application.
Ruby
374
star
19

analytics-android

The hassle-free way to add analytics to your Android app.
Java
373
star
20

analytics-react-native

The hassle-free way to add analytics to your React-Native app.
TypeScript
337
star
21

consent-manager

Drop-in consent management plugin for analytics.js
TypeScript
326
star
22

parquet-go

Go library to read/write Parquet files
Go
314
star
23

ts-mysql-plugin

A typescript language service plugin that gives superpowers to SQL tagged template literals.
TypeScript
312
star
24

analytics-next

Segment Analytics.js 2.0
TypeScript
294
star
25

specs

Peer into your ECS clusters
JavaScript
273
star
26

fasthash

Go package porting the standard hashing algorithms to a more efficient implementation.
Go
261
star
27

ctlstore

Control Data Store
Go
256
star
28

ware

Easily create your own middleware layer.
JavaScript
254
star
29

analytics-php

The hassle-free way to integrate analytics into any php application.
PHP
252
star
30

analytics-python

The hassle-free way to integrate analytics into any python application.
Python
231
star
31

chrome-sidebar

Easiest way to embed an iframe as a chrome extension
JavaScript
208
star
32

typewriter

Type safety + intellisense for your Segment analytics
TypeScript
206
star
33

nsq.js

NSQ client for nodejs
JavaScript
203
star
34

stats

Go package for abstracting stats collection
Go
202
star
35

threat-modeling-training

Segment's Threat Modeling training for our engineers
197
star
36

in-eu

๐Ÿ‡ช๐Ÿ‡บ privacy first EU detection library for browsers
JavaScript
180
star
37

kubectl-curl

Kubectl plugin to run curl commands against kubernetes pods
Go
167
star
38

go-prompt

Go terminal prompts.
Go
167
star
39

is-url

Loosely validate a URL.
JavaScript
160
star
40

cwlogs

CLI tool for reading logs from Cloudwatch Logs
Go
142
star
41

kubeapply

A lightweight tool for git-based management of Kubernetes configs
Go
141
star
42

analytics-go

Segment analytics client for Go
Go
136
star
43

analytics.js-core

The hassle-free way to integrate analytics into any web application.
TypeScript
132
star
44

dependency-report

Generate usage reports of your JS dependencies
JavaScript
129
star
45

ecs-logs

Log forwarder for services ran by ecs-agent.
Go
115
star
46

analytics-java

The hassle-free way to integrate analytics into any java application.
Java
113
star
47

analytics.js-integrations

Monorepo housing Segment's analytics.js integrations
JavaScript
112
star
48

go-athena

Golang database/sql driver for AWS Athena
Go
107
star
49

Analytics.NET

The hassle-free way to integrate analytics into any C# / .NET application.
C#
107
star
50

go-queue

NSQ consumer convenience layer.
Go
104
star
51

xml-parser

simple non-compliant xml parser for nodejs
JavaScript
101
star
52

backo

exponential backoff without the weird cruft
JavaScript
99
star
53

analytics-vue

The hassle-free way to integrate analytics into your Vue application.
Vue
98
star
54

nsq-go

Go package providing tools for building NSQ clients, servers and middleware.
Go
94
star
55

consul-go

Go package providing building blocks for interacting with Consul.
Go
90
star
56

analytics-swift

The hassle-free way to add Segment analytics to your Swift app (iOS/tvOS/watchOS/macOS/Linux).
Swift
89
star
57

frictionless-signup

Reduce friction and increase customer data in your online forms using Segment & Clearbit
JavaScript
86
star
58

superagent-retry

Retry superagent requests for common hangups
JavaScript
85
star
59

pg-escape

sprintf-style postgres query escaping and helper functions
JavaScript
84
star
60

conf

Go package for loading program configuration from multiple sources.
Go
81
star
61

orbital

๐Ÿš€๐ŸŒ A simple end-to-end testing framework for Go
Go
80
star
62

functions-library

A library of example functions to use with the Segment Developer Center
JavaScript
75
star
63

inbound

A url and referrer parsing library for node.
JavaScript
72
star
64

decibel

A small iOS app for recording office noise dB levels to Datadog.
Swift
69
star
65

analytics-angular

The hassle-free way to integrate analytics into your Angular application.
TypeScript
68
star
66

events

Go package for routing, formatting and publishing events produced by a program.
Go
62
star
67

glue

Generate typed Golang RPC clients from server code
Go
60
star
68

pingdummy

Example application for segmentio/stack
JavaScript
60
star
69

go-loggly

Loggly client for Go
Go
59
star
70

analytics-rust

Segment analytics client for Rust
Rust
55
star
71

retrofit-jsonrpc

Json-RPC with Retrofit.
Java
54
star
72

snippet

Render the analytics.js snippet.
JavaScript
53
star
73

nsq_to_redis

NSQ โœˆ Redis {pubsub, capped lists}
Go
52
star
74

segment-proxy

Proxies requests to the Segment CDN and Tracking API.
Go
51
star
75

is-email

Component: loosely validate an email address.
JavaScript
49
star
76

statsy

Simple statsd client for nodejs
JavaScript
49
star
77

sherlock

A pluggable service-detection tool
JavaScript
49
star
78

objconv

A Go package exposing encoder and decoders that support data streaming to and from multiple formats.
Go
49
star
79

cli

Go package providing high-level constructs for command-line tools.
Go
48
star
80

facade

Providing common fields for analytics integrations, since 2013.
JavaScript
47
star
81

agecache

An LRU cache with support for max age
Go
47
star
82

validate-form

Easily validate a form element against a set of rules.
JavaScript
44
star
83

go-stats

Go stats ticker utility
Go
44
star
84

go-snakecase

Faster snakecase implementation
Go
43
star
85

utm-params

parse and get all utm parameters
JavaScript
42
star
86

aws-billing

An API to learn how much your AWS hosting costs every month
JavaScript
39
star
87

action-destinations

Action Destinations are the new way to build streaming destinations on Segment.
TypeScript
38
star
88

testdemo

Examples for https://segment.com/blog/5-advanced-testing-techniques-in-go/
Go
38
star
89

data-digger

Dig through structured messages in Kafka, S3, or local files
Go
37
star
90

feature

Feature gate database designed for simplicity and efficiency.
Go
36
star
91

segment-docs

Segment Documentation. Powered by Jekyll.
HTML
36
star
92

redis-go

Go package providing tools for building redis clients, servers and middleware.
Go
36
star
93

http_to_nsq

Publishes HTTP requests to NSQD (for CI webhooks etc)
Go
36
star
94

analytics.js-integration

The base integration factory used to create custom analytics integrations for analytics.js.
JavaScript
35
star
95

ebs-backup

Backup EBS Volumes
Go
34
star
96

Analytics.Xamarin

Analytics for Xamarin, a portable class library supporting iOS, Android, Mac OS, and others.
C#
34
star
97

go-hll

Go implementation of HLL that plays nicely with other languages
Go
34
star
98

terraform-segment-data-lakes

Terraform modules which create AWS resources for a Segment Data Lake.
HCL
34
star
99

analytics-kotlin

The hassle-free way to add Segment analytics to your Kotlin app (Android/JVM).
Kotlin
32
star
100

errors-go

Go package providing various error handling primitives.
Go
32
star