14 | Segment collects analytics data and sends it to 250+ apps with the flip of a switch (e.g. Google Analytics, Mixpanel, Optimizely, Facebook Ads, Slack, Sentry). You only need one snippet and you can turn integrations on and off whenever you want with no additional code.
15 |
16 |
17 | );
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/Main.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Switch, Route } from 'react-router-dom';
3 | import Home from './Home';
4 | import About from './About';
5 | import './Main.css';
6 |
7 | const Main = ({ trackClickEvent }) => (
8 |
6 |
7 | 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.
8 |
9 | ## How to get started
10 | 1. **Collect analytics data** from your app(s).
11 | - The top 200 Segment companies collect data from 5+ source types (web, mobile, server, CRM, etc.).
12 | 2. **Send the data to analytics tools** (for example, Google Analytics, Amplitude, Mixpanel).
13 | - 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.
14 | 3. **Explore your data** by creating metrics (for example, new signups, retention cohorts, and revenue generation).
15 | - The best Segment companies use retention cohorts to measure product market fit. Netflix has 70% paid retention after 12 months, 30% after 7 years.
16 |
17 | [Segment](https://segment.com?utm_source=github&utm_medium=click&utm_campaign=protos_react) 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](https://app.segment.com/signup?utm_source=github&utm_medium=click&utm_campaign=protos_react).
18 |
19 | ### Why?
20 | 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.
21 |
22 | 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.
23 |
24 | 3. **Send data from anywhere**. Send Segment data from any device, and we'll transform and send it on to any tool.
25 |
26 | 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.
27 |
28 | For example, you can capture data on any app:
29 | ```js
30 | analytics.track('Order Completed', { price: 99.84 })
31 | ```
32 | Then, query the resulting data in SQL:
33 | ```sql
34 | select * from app.order_completed
35 | order by price desc
36 | ```
37 |
38 | ### 🚀 Startup Program
39 |
40 |
41 |
42 | 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!
43 |
44 | # 🏃💨 Quickstart
45 | 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](https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/?utm_source=github&utm_medium=click&utm_campaign=protos_react). 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!
46 |
47 | Start sending data from any [source](https://segment.com/docs/connections/sources/?utm_source=github&utm_medium=click&utm_campaign=protos_react) and see events live in the Segment **debugger**:
48 |
49 |
50 |
51 |
52 |
53 |
54 | Once you have data being sent to Segment, forward this data to any of our 250+ [destinations](https://segment.com/docs/connections/destinations/catalog/?utm_source=github&utm_medium=click&utm_campaign=protos_react):
55 |
56 |
57 |
58 |
59 |
60 | # 🔌 Installing on Your App
61 | How do you get this in your own React app? Follow the steps below.
62 |
63 | ## ✂️ Step 1: Copy the Snippet
64 | To install Segment in your own app first [sign up](https://app.segment.com/signup?utm_source=github&utm_medium=click&utm_campaign=protos_react) with Segment and locate your Segment project's **Write Key**.
65 | 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.
66 |
67 | > **Tip!** You can find your write key in your Segment project setup guide or settings.
68 |
69 | ```html
70 |
76 | ```
77 | Now `window.analytics` is loaded and available to use throughout your app!
78 |
79 | **Note**: If you are seeing compilation errors, you may need to declare the `windows` interface as a global:
80 |
81 | ```JS
82 | declare global {
83 | interface Window { analytics: any; }
84 | }
85 | ```
86 |
87 | 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.
88 |
89 | ## 📱 Step 2: Track Page Views in an SPA
90 | > **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.
91 |
92 | 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.
93 |
94 | 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](https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/#page?utm_source=github&utm_medium=click&utm_campaign=protos_react).
95 |
96 | 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](https://reacttraining.com/react-router) and React's lifecycle methods to create `page` calls.
97 |
98 | If you separate your pages into their own components and allow the [``](https://reacttraining.com/react-router/core/api/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.
99 |
100 | ```JSX
101 | export default class HomePage extends Component {
102 | componentDidMount() {
103 | window.analytics.page('Home');
104 | }
105 |
106 | render() {
107 | return (
108 |
109 | Home page.
110 |
111 | );
112 | }
113 | }
114 | ```
115 |
116 | ## 🔍 Step 3: Identify Users
117 | 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](https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/#identify?utm_source=github&utm_medium=click&utm_campaign=protos_react).
118 |
119 | **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`.
120 |
121 | Here's what a basic call to `identify` might look like:
122 |
123 | ```javascript
124 | window.analytics.identify('f4ca124298', {
125 | name: 'Michael Bolton',
126 | email: 'mbolton@initech.com'
127 | });
128 | ```
129 |
130 | This call identifies Michael by his unique User ID and labels him with `name` and `email` traits.
131 |
132 | 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:
133 |
134 | ```js
135 | export default class IdentifyForm extends Component {
136 | state = {
137 | name: '',
138 | email: ''
139 | };
140 |
141 | handleChange(event) {
142 | this.setState({ value: event.target.value });
143 | }
144 |
145 | handleSubmit() {
146 | const { name, email } = this.state;
147 |
148 | // Add your own unique ID here or we will automatically assign an anonymousID
149 | window.analytics.identify({
150 | name,
151 | email
152 | });
153 | }
154 |
155 | render() {
156 | const { name, email } = this.state;
157 |
158 | return (
159 |
164 | );
165 | }
166 | }
167 | ```
168 |
169 | > **Tip!** Other handlers might be better for other situations. You can see the [React docs on event handlers](https://reactjs.org/docs/handling-events.html) for more information.
170 |
171 | ## ⏰ Step 4: Track Actions
172 | 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](https://segment.com/docs/protocols/data-quality/whats-a-tracking-plan/?utm_source=github&utm_medium=click&utm_campaign=protos_react). You can read more about `track` in the [track reference](https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/#track?utm_source=github&utm_medium=click&utm_campaign=protos_react).
173 |
174 | Here's what a call to `track` might look like when a user bookmarks an article:
175 |
176 | ```javascript
177 | window.analytics.track('Article Bookmarked', {
178 | title: 'Snow Fall',
179 | subtitle: 'The Avalanche at Tunnel Creek',
180 | author: 'John Branch'
181 | });
182 | ```
183 |
184 | 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.
185 |
186 | ### Track Calls with Event Handlers
187 | 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`.
188 |
189 | ```JSX
190 | export default class SignupButton extends Component {
191 | trackEvent() {
192 | window.analytics.track('User Signup');
193 | }
194 |
195 | render() {
196 | return (
197 |
200 | );
201 | }
202 | }
203 | ```
204 |
205 | > **Tip!** Other handlers might be better for other situations. You can see the [React docs on event handlers](https://reactjs.org/docs/handling-events.html) for more information.
206 |
207 | ### Track Calls with Lifecycle Methods
208 | [Lifecycle methods](https://reactjs.org/docs/react-component.html#the-component-lifecycle) 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:
209 |
210 | ```JSX
211 | export default class VideoPlayer extends Component {
212 | componentDidMount() {
213 | window.analytics.track('Video Played');
214 | }
215 |
216 | render() {
217 | return (
218 |
221 | );
222 | }
223 | }
224 | ```
225 |
226 | ## 🤔 What's next?
227 | 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. 🎉
228 |
229 | ## 🎓 Advanced
230 | Once you've mastered the basics, here are some advanced use cases you can apply with Segment.
231 |
232 | ### Track Calls for Error Logging
233 | 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.
234 |
235 | ```JSX
236 | export default class ErrorBoundary extends Component {
237 | static propTypes = {
238 | /**
239 | * Fallback component to display when uncaught exceptions occur in a component tree:
240 | * function({ error: PropTypes.object, errorInfo: PropTypes.object }): PropTypes.node
241 | */
242 | errorComponent: PropTypes.func
243 | };
244 |
245 | static defaultProps = {
246 | errorComponent: () => null
247 | };
248 |
249 | state = {
250 | error: null,
251 | errorInfo: null
252 | };
253 |
254 | componentDidCatch(error, errorInfo) {
255 | const { error, errorInfo } = this.state;
256 |
257 | this.setState({
258 | error,
259 | errorInfo
260 | });
261 |
262 | window.analytics.track('JavaScript Error', {
263 | error,
264 | errorInfo
265 | });
266 | }
267 |
268 | render() {
269 | const { error, errorInfo } = this.state;
270 | const { errorComponent: ErrorComponent, children } = this.props;
271 |
272 | return error ? (
273 |
277 | ) : (
278 | children
279 | );
280 | }
281 | }
282 | ```
283 |
284 | ### Typechecking with PropTypes
285 | You can use typechecking with [`prop-types`](https://reactjs.org/docs/typechecking-with-proptypes.html) 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`:
286 |
287 | ```JSX
288 | export default class User extends Component {
289 | static propTypes = {
290 | id: PropTypes.string,
291 | identifyTraits: PropTypes.shape({
292 | name: PropTypes.string.isRequired,
293 | email: PropTypes.string.isRequired,
294 | isAuthorized: PropTypes.bool.isRequired
295 | }),
296 | trackTitle: PropTypes.string,
297 | trackTraits: PropTypes.object
298 | };
299 |
300 | identify() {
301 | const { id, identifyTraits } = this.props;
302 |
303 | window.analytics.identify(id, identifyTraits);
304 | }
305 |
306 | track() {
307 | const { trackTitle, trackTraits } = this.props;
308 |
309 | window.analytics.track(trackTitle, trackTraits);
310 | }
311 |
312 | render() {
313 | const { children } = this.props;
314 |
315 | return children;
316 | }
317 | }
318 | ```
319 |
320 | If you love typechecking, you'll love our open-source project [typewriter](https://github.com/segmentio/typewriter), which enforces a strongly-typed tracking spec via a JSON schema. Interested more in data standardization? Check out our [protocols product](https://segment.com/product/protocols?utm_source=github&utm_medium=click&utm_campaign=protos_react) to improve data quality.
321 |
322 | 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](https://segment.com/product/warehouses?utm_source=github&utm_medium=click&utm_campaign=protos_react), 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.
323 |
324 | ## 💾 Warehouses
325 | 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.
326 |
327 | Examples of data warehouses include Amazon Redshift, Google BigQuery, MySQL, and Postgres.
328 |
329 |
330 |
331 |
332 |
333 | ## 📺 Demo
334 | To start with this demo app, follow the instructions below:
335 |
336 | 1. [Sign up](https://app.segment.com/signup?utm_source=github&utm_medium=click&utm_campaign=protos_react) with Segment and edit the snippet in [index.html](https://github.com/segmentio/analytics-react/blob/master/public/index.html#L28) to replace `YOUR_WRITE_KEY` with your Segment **Write Key**.
337 | > **Tip!** You can find your key in your project setup guide or settings in the Segment.
338 |
339 | Your snippet will look something like the example below.
340 |
341 | ```html
342 |
347 | ```
348 |
349 | 2. From the command line, use `npm install` to install the dependencies, then `npm start` to run the app.
350 | ```bash
351 | npm install
352 | npm start
353 | ```
354 |
355 | 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:
356 | - Page event: `Home` - When someone views the `home` page.
357 | - Page event: `About` - When someone views the `about` page.
358 | - Track event: `Learn React Link Clicked` - When someone clicks the "Learn React" link.
359 |
360 | Congrats! You're seeing live data from your demo React app in Segment! 🎉
361 |
362 | ## 🔒 What about privacy?
363 | Want to allow your visitors to control and customize their tracking preferences on your site? Integrate our [consent-manager](https://github.com/segmentio/consent-manager), which is imported via the snippet and uses our pre-built React component under the hood.
364 |
365 | ## 📝 Docs & Feedback
366 | Check out our full [Analytics.js reference](https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/#track?utm_source=github&utm_medium=click&utm_campaign=protos_reactutm_source=github&utm_medium=click&utm_campaign=protos_react) to see what else is possible, or read about the [Tracking API methods](https://segment.com/docs/connections/sources/catalog/libraries/server/http-api/?utm_source=github&utm_medium=click&utm_campaign=protos_react) to get a sense for the bigger picture. If you have any questions, or see anywhere we can improve our documentation, [let us know](https://segment.com/contact?utm_source=github&utm_medium=click&utm_campaign=protos_react)!
367 |
--------------------------------------------------------------------------------