Code Monkey home page Code Monkey logo

Comments (4)

iksent avatar iksent commented on July 19, 2024 7

2021 hooks solution

  1. 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
  1. _app.tsx: Just wrap your layout with <WithYandexMetrika> like with other providers
  2. Set process.env.YANDEX_METRIKA_ID environment variable to your ID
  3. Don't forget to pass env vars to client

from react-yandex-metrika.

dimuska139 avatar dimuska139 commented on July 19, 2024 5

@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.

vvmspace avatar vvmspace commented on July 19, 2024

+1 Add examples of using with NextJS

from react-yandex-metrika.

olegyablokov avatar olegyablokov commented on July 19, 2024

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.