1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00

Add with-react-ga example (#2225)

* add with-react-ga example

* fix title in Readme
This commit is contained in:
Vinay Puppal 2017-06-10 03:14:26 +05:30 committed by Tim Neutkens
parent c66cafd362
commit 7b62184c0b
6 changed files with 102 additions and 0 deletions

View file

@ -0,0 +1,29 @@
[![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.

View file

@ -0,0 +1,19 @@
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>
)
}
}

View file

@ -0,0 +1,17 @@
{
"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"
}

View file

@ -0,0 +1,7 @@
import Layout from '../components/Layout'
export default () => (
<Layout>
<div>About us</div>
</Layout>
)

View file

@ -0,0 +1,6 @@
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>
)

View file

@ -0,0 +1,24 @@
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 })
}
}