YanivNis
YanivNis

Reputation: 31

Adding JS code snippets (full story, mixpanel, etc.) to Docusaurus.io

I'm trying to find out how can I add JS code snippets to work with Docusaurus.io (https://docusaurus.io). I want to add some analytics tools to my Docusaurus based web documentation such as - mixpanel, full story, etc. but I didn't find how can I do it.

Upvotes: 3

Views: 2629

Answers (3)

Linghua Jin
Linghua Jin

Reputation: 569

https://docusaurus.io/docs/swizzling#wrapper-your-site-with-root

import React from 'react';
import mixpanel from 'mixpanel-browser';

// Default implementation, that you can customize
export default function Root({children}) {
  React.useEffect(() => {
    if (typeof window !== 'undefined') {
      // Initialize Mixpanel with the token
      mixpanel.init(TOKEN, {
        track_pageview: true,
        debug: process.env.NODE_ENV === 'development'
      });
    }
  }, []);

  return <>{children}</>;
}

Upvotes: 0

morpheus
morpheus

Reputation: 20382

For me this worked:

Step 1: Install mixpanel SDK:

npm i -D --save mixpanel-browser

Step 2: Create a file src/theme/Layout.js with following in it:

import React, { useEffect } from 'react';
import OriginalLayout from '@theme-original/Layout';
import mixpanel from 'mixpanel-browser';

export default function Layout(props) {
  useEffect(() => {
    // Initialize Mixpanel
    // https://docs.mixpanel.com/docs/quickstart/install-mixpanel?sdk=javascript
    mixpanel.init('INSERT_TOKEN_HERE', {
      debug: true,
      track_pageview: true,
      persistence: 'localStorage',
    });

    // Optional: Track initial page view
    mixpanel.track('Page View', {
      path: window.location.pathname,
    });
  }, []);

  return <OriginalLayout {...props} />;
}

This solution is w.r.t. Docusaurus 3.6.3

Upvotes: 1

Richard Zhang
Richard Zhang

Reputation: 350

I am not sure exactly where you'd like to put JS snippet in. Here are some scenarios in Docusaurus.

You may add JS file to siteConfig.js, this section:

scripts: ['https://buttons.github.io/buttons.js'],

If you'd like to add JS snippet to pages, then it is doable since each page is just a React component. Something like this in your render method:

<script type="text/javascript" dangerouslySetInnerHTML={{__html: js_snippet}} />

If you'd like to add JS snippet to docs I think it is pretty hard because docs are in markdown which I don't think you can add script tag.

Hope this helps.

Upvotes: -1

Related Questions