Comments (4)
2021 hooks solution
- Create new React component
WithYandexMetrika.tsx
:
import React, { ReactNode, useCallback, useEffect } from 'react'
import Router from 'next/router'
import ym, { YMInitializer } from 'react-yandex-metrika'
export type WithYandexMetrikaProps = {
children: ReactNode
}
const enabled =
process.env.NODE_ENV === 'production' &&
process.env.YANDEX_METRIKA_ID
const WithYandexMetrika = (props: WithYandexMetrikaProps) => {
const { children } = props
const hit = useCallback((url) => {
if (enabled) {
ym('hit', url)
} else {
console.log(`%c[YandexMetrika](HIT)`, `color: orange`, url)
}
}, [])
useEffect(() => {
hit(window.location.pathname + window.location.search)
Router.events.on('routeChangeComplete', (url: string) => hit(url))
}, [])
return (
<>
{enabled && (
<YMInitializer
accounts={[Number(process.env.YANDEX_METRIKA_ID)]}
options={{ webvisor: true, defer: true }}
version="2"
/>
)}
{children}
</>
)
}
export default WithYandexMetrika
_app.tsx:
Just wrap your layout with<WithYandexMetrika>
like with other providers- Set
process.env.YANDEX_METRIKA_ID
environment variable to your ID - Don't forget to pass env vars to client
from react-yandex-metrika.
@vvmspace my current realization:
_app.tsx (custom _app.tsx)
import Router from 'next/router';
import {YMInitializer} from "react-yandex-metrika";
...
Router.events.on('routeChangeComplete', (url: string) => {
// To hit only in production and only on client side (in browser)
if (typeof window !== 'undefined' && process.env.NODE_ENV === 'production') {
ym('hit', url);
}
});
class MyApp extends App {
componentDidMount() {
// To hit only in production and only on client side (in browser)
if (typeof window !== 'undefined' && process.env.NODE_ENV === 'production') {
const url = window.location.pathname + window.location.search;
ym('hit', url);
}
...
}
...
render () {
// @ts-ignore
const {Component, pageProps, reduxStore, layoutProps} = this.props;
return (
<>
{process.env.NODE_ENV === 'production' &&
<YMInitializer
accounts={[parseInt(process.env.YM_COUNTER_ID as string)]}
options={{webvisor: true, defer: true}}
version="2"
/>
}
<Provider store={reduxStore}>
<ThemeProvider theme={theme}>
<CssBaseline />
<Layout {...layoutProps}>
<Component {...pageProps} />
</Layout>
</ThemeProvider>
</Provider>
</>
)
}
}
from react-yandex-metrika.
+1 Add examples of using with NextJS
from react-yandex-metrika.
I have an e-commerce website that needs to have SSR for SEO purposes. useEffect
in the root layout won't work because it is for client components. Anyone knows what can be done here?
from react-yandex-metrika.
Related Issues (20)
- API для отправки запросов в конкретный счетчик HOT 2
- example for use HOT 10
- TypeError: window[_constants.accountListName] is undefined HOT 13
- В версии v2.4.0 ломается минификацию проекта HOT 3
- настройка дополнительных параметров HOT 12
- Как вызвать метод params HOT 1
- Не считается время на странице, вебвизор без верстки HOT 6
- Ошибка после добавления ym HOT 8
- Не найден HOT 4
- Новая версия методов HOT 4
- Ошибка после перехода на версию 2.5.0 HOT 1
- Добавьте changelog пожалуйста
- Проблема с инициализацией
- Изменение тега-обёртки для скрипта
- Как передать userParams HOT 2
- Добавить метод ym.init() HOT 1
- Initializing multiple accounts with different options
- SSR (Nextjs) + react-yandex-metrika
- js CDN provider HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from react-yandex-metrika.