Commit 6c4d9123 authored by goncy's avatar goncy

Update example

parent 0e7e62de
NEXT_PUBLIC_GOOGLE_ANALYTICS_UA=
\ No newline at end of file
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local
# vercel
.vercel
## Example app using `next/script`
This example shows how to use Next.js along with `next/script` component. Before the release of `next/script` you had to use a `<script>` along with `dangerouslySetInnerHTML` to load third party browser libraries like [Google Analytics](../with-google-analytics). We will create a component that loads the script and saves the added global variable to a local state.
## Deploy your own
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/script-component&project-name=script-component&repository-name=script-component)
## How to use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:
```bash
npx create-next-app --example script-component script-component-app
# or
yarn create next-app --example script-component script-component-app
```
Next, copy the `.env.local.example` file in this directory to `.env.local` (which will be ignored by Git):
```bash
cp .env.local.example .env.local
```
Set the `NEXT_PUBLIC_GOOGLE_ANALYTICS_UA` variable in `.env.local` to match your Google Tag Manager ID.
Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
import Script from "next/script"
function Analytics({onLoad}) {
function handleLoad() {
const {ga} = window;
ga('create', process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS_UA, 'auto');
ga('send', 'pageview');
return onLoad({
track: (name) => ga('send', name)
})
}
return (
<Script onLoad={handleLoad} strategy="afterInteractive" src="https://www.google-analytics.com/analytics.js" />
)
}
export default Analytics
\ No newline at end of file
{
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "latest",
"react": "^17.0.2",
"react-dom": "^17.0.2"
}
}
import { useState } from "react"
import Analytics from "../components/Analytics"
export default function Home() {
const [analytics, setAnalytics] = useState(null)
function handleEvent() {
analytics.track('test')
}
return (
<div>
<h1>
Open Dev Tools network panel to inspect events
</h1>
<nav>
<button onClick={handleEvent}>Track event</button>
</nav>
<Analytics onLoad={setAnalytics} />
</div>
)
}
export const GA_TRACKING_ID = process.env.NEXT_PUBLIC_GA_ID
// https://developers.google.com/analytics/devguides/collection/gtagjs/pages
export const pageview = (url) => {
window.gtag('config', GA_TRACKING_ID, {
page_path: url,
})
}
// https://developers.google.com/analytics/devguides/collection/gtagjs/events
export const event = ({ action, category, label, value }) => {
window.gtag('event', action, {
event_category: category,
event_label: label,
value: value,
})
}
import { useEffect } from 'react'
import { useState } from 'react'
import Script from 'next/script'
import { useRouter } from 'next/router'
import * as gtag from '../lib/gtag'
const App = ({ Component, pageProps }) => {
const [ga, setGa] = useState(null);
const router = useRouter()
useEffect(() => {
const handleRouteChange = (url) => {
gtag.pageview(url)
}
router.events.on('routeChangeComplete', handleRouteChange)
return () => {
router.events.off('routeChangeComplete', handleRouteChange)
}
}, [router.events])
function handleLoad() {
const {ga} = window;
setGa(() => ga)
ga('create', process.env.NEXT_PUBLIC_GA_ID, 'auto')
router.events.on('routeChangeComplete', () => ga('send', 'pageview'))
}
function handleTrack({action, category, label}) {
ga('send', 'event', action, category, label)
}
return (
<>
{/* Global Site Tag (gtag.js) - Google Analytics */}
<Script
strategy="afterInteractive"
src={`https://www.googletagmanager.com/gtag/js?id=${gtag.GA_TRACKING_ID}`}
/>
<Script
id="gtag-init"
strategy="afterInteractive"
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${gtag.GA_TRACKING_ID}', {
page_path: window.location.pathname,
});
`,
}}
/>
<Component {...pageProps} />
<Script onLoad={handleLoad} strategy="afterInteractive" src="https://www.google-analytics.com/analytics.js" />
<Component {...pageProps} onTrack={handleTrack} />
</>
)
}
......
import { Component } from 'react'
import { useState } from 'react'
import Page from '../components/Page'
import * as gtag from '../lib/gtag'
const Contact = ({onTrack}) => {
const [message, setMessage] = useState("")
export default class Contact extends Component {
state = { message: '' }
handleInput = (e) => {
this.setState({ message: e.target.value })
function handleInput (e) {
setMessage(e.target.value)
}
handleSubmit = (e) => {
function handleSubmit(e) {
e.preventDefault()
gtag.event({
action: 'submit_form',
category: 'Contact',
label: this.state.message,
onTrack({
action: 'Contact',
category: 'submit_form',
label: message
})
this.setState({ message: '' })
setMessage('')
}
render() {
return (
<Page>
<h1>This is the Contact page</h1>
<form onSubmit={this.handleSubmit}>
<label>
<span>Message:</span>
<textarea onChange={this.handleInput} value={this.state.message} />
</label>
<button type="submit">submit</button>
</form>
</Page>
)
}
return (
<Page>
<h1>This is the Contact page</h1>
<form onSubmit={handleSubmit}>
<label>
<span>Message:</span>
<textarea onChange={handleInput} value={message} />
</label>
<button type="submit">submit</button>
</form>
</Page>
)
}
export default Contact
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment