Giter Club home page Giter Club logo

matomo-react's Introduction

Matomo React

Stand alone library for using Matamo tracking in React projects. Originally forked from @datapunt/matomo-react. Since he abandoned the project I forked the part of it containing React specific logic since I needed it for a project. I have not tested most of the functionality yet, so there's no guarantee of everything working. Will probably get to test most parts as I wo forward from here. Most of the credits for the code belongs to @datapunt.

Installation

yarn add matomo-react

Usage

To use this you need to create a Matomo instance with your project specific details, and wrap your application with the MatomoProvider that this package exposes.

import { MatomoProvider, createInstance } from 'matomo-react'

const instance = createInstance({
  urlBase: 'https://LINK.TO.DOMAIN',
  siteId: 3,
  userId: 'UID76903202', // optional, default value: `undefined`.
  trackerUrl: 'https://LINK.TO.DOMAIN/tracking.php', // optional, default value: `${urlBase}matomo.php`
  srcUrl: 'https://LINK.TO.DOMAIN/tracking.js', // optional, default value: `${urlBase}matomo.js`
  permanentTitle: 'My Awesome App', // optional, always use this title for tracking, ignores document.title. Useful for SPAs.
  permanentHref: '/', // optional, always use this href for tracking, ignores window.location.href. Useful for SPAs.
  disabled: false, // optional, false by default. Makes all tracking calls no-ops if set to true.
  heartBeat: {
    // optional, enabled by default
    active: true, // optional, default value: true
    seconds: 10, // optional, default value: 15
  },
  linkTracking: false, // optional, default value: true
  configurations: {
    // optional, default value: {}
    // any valid matomo configuration, all below are optional
    disableCookies: true,
    setSecureCookie: true,
    setRequestMethod: 'POST',
  },
})

ReactDOM.render(
  <MatomoProvider value={instance}>
    <MyApp />
  </MatomoProvider>,
)

After wrapping your application with the MatomoProvider you can use the useMatomo hook to track your application from anywhere within the MatomoProvider component tree:

import React from 'react'
import { useMatomo } from 'matomo-react'

const MyPage = () => {
  const { trackPageView, trackEvent } = useMatomo()

  // Track page view
  React.useEffect(() => {
    trackPageView()
  }, [])

  const handleOnClick = () => {
    // Track click on button
    trackEvent({ category: 'sample-page', action: 'click-event' })
  }

  return (
    <button type="button" onClick={handleOnClick}>
      Click me
    </button>
  )
}

Advanced usage

By default we send the window's document title and location, or send your own values. Also, custom dimensions can be used:

import React from 'react'
import { useMatomo } from 'matomo-react'

const MyPage = () => {
  const { trackPageView, trackEvent } = useMatomo()

  // Track page view
  React.useEffect(() => {
    trackPageView({
      documentTitle: 'Page title', // optional
      href: 'https://LINK.TO.PAGE', // optional
      customDimensions: [
        {
          id: 1,
          value: 'loggedIn',
        },
      ], // optional
    })
  }, [])

  const handleOnClick = () => {
    // Track click on button
    trackEvent({ category: 'sample-page', action: 'click-event' })
  }

  return (
    <button type="button" onClick={handleOnClick}>
      Click me
    </button>
  )
}

And you can do the same for the trackEvent method:

import React from 'react'
import { useMatomo } from 'matomo-react'

const MyPage = () => {
  const { trackEvent } = useMatomo()

  const handleOnClick = () => {
    // Track click on button
    trackEvent({
      category: 'sample-page',
      action: 'click-event',
      name: 'test', // optional
      value: 123, // optional, numerical value
      documentTitle: 'Page title', // optional
      href: 'https://LINK.TO.PAGE', // optional
      customDimensions: [
        {
          id: 1,
          value: 'loggedIn',
        },
      ], // optional
    })
  }

  return (
    <button type="button" onClick={handleOnClick}>
      Click me
    </button>
  )
}

The useMatomo hook also exposes the following methods:

  • trackEvents()
  • trackSiteSearch()
  • trackLink()
  • pushInstruction()

For example, the pushInstruction() function can be used to push instructions to Matomo for execution. This is equivalent to pushing entries into the _paq array.

const { pushInstruction } = useMatomo()
pushInstruction('setUserId', 'USER_ID_HERE')

SPA Link Tracking

Matomo provides the option to track outbound link, however, this implementation is flaky for a SPA (Single Page Application) without SSR (Server Side Rendering) across different versions of Matomo. Therefore you can use the enableLinkTracking method to listen to outbound clicks on anchor elements. This method should be placed on a component directly below your MatomoProvider on a component that's rendered on every page view. Also, make sure to disable the linkTracking option on the instance passed to the provider to prevent Matomo from catching some link clicks:

import { MatomoProvider, createInstance, useMatomo } from 'matomo-react'

const instance = createInstance({
  urlBase: "https://LINK.TO.DOMAIN",
  linkTracking: false // Important!
});

ReactDOM.render(
  <MatomoProvider value={instance}>
    <MyApp />
  </MatomoProvider>
)

const MyApp = () => {
  const { enableLinkTracking } = useMatomo()

  enableLinkTracking()

  return (
    // Render components
  )
}

References

matomo-react's People

Contributors

iulianraduat avatar maxfahl avatar

Watchers

 avatar

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.