提交 7b62184c 编写于 作者: V Vinay Puppal 提交者: Tim Neutkens

Add with-react-ga example (#2225)

* add with-react-ga example

* fix title in Readme
上级 c66cafd3
[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-react-ga)
# React-GA example
## How to use
Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-react-ga
cd with-react-ga
```
Install it and run:
```bash
npm install
npm run dev
```
Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download))
```bash
now
```
## The idea behind the example
This example shows the most basic way to use [react-ga](https://github.com/react-ga/react-ga) using `<Layout/>` component with NextJs. You can also use an HOC instead of `<Layout/>` component. Modify `Tracking ID` in `utils/analytics.js` file for testing this example.
import React from 'react'
import { initGA, logPageView } from '../utils/analytics'
export default class Layout extends React.Component {
componentDidMount () {
if (!window.GA_INITIALIZED) {
initGA()
window.GA_INITIALIZED = true
}
logPageView()
}
render () {
return (
<div>
{this.props.children}
</div>
)
}
}
{
"name": "hello-world",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "*",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"react-ga": "2.2.0"
},
"author": "",
"license": "ISC"
}
import Layout from '../components/Layout'
export default () => (
<Layout>
<div>About us</div>
</Layout>
)
import Link from 'next/link'
import Layout from '../components/Layout'
export default () => (
<Layout><div>Hello World. <Link href='/about'><a>About</a></Link></div></Layout>
)
import ReactGA from 'react-ga'
export const initGA = () => {
console.log('GA init')
ReactGA.initialize('UA-xxxxxxxxx-1')
}
export const logPageView = () => {
console.log(`Logging pageview for ${window.location.pathname}`)
ReactGA.set({ page: window.location.pathname })
ReactGA.pageview(window.location.pathname)
}
export const logEvent = (category = '', action = '') => {
if (category && action) {
ReactGA.event({ category, action })
}
}
export const logException = (description = '', fatal = false) => {
if (description) {
ReactGA.exception({ description, fatal })
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册