How to remove some code from a parent component on a page without making any changes to the parent component in React?

94 Views Asked by At

So I have a parent component called Layout.jsx which contains the general stuff required on the website like nav bar and meta tags. It also has a Google tag which tracks the analytics for the entire website. I now have a webpage which I use for Google Ads and I need to add a separate google tag code to track actions on this webpage. But now there are two google tags on the page. I want to remove the general one which is for the entire website from this webpage without removing it for other webpages.

Here is my code Layout.jsx :

<Helmet>
    <title>{title}</title>
    <meta name="msapplication-TileColor" content="#ffffff" />
    <meta name="theme-color" content={color} />
    <meta
      name="google-site-verification"
    />
    <meta property="og:type" content="website" />
    <meta property="og:title" content={title} />
    <meta
      property="og:description"
    />
    <meta property="og:locale" content="en_IN" />
    <meta name="twitter:card" content="summary_large_image" />
    
    <script
      async
      src="https://www.googletagmanager.com/gtag/js?id=G-{tag}"
    ></script>
    <script>
      {`
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'G-{tag}');
      `}
    </script>

    ;
  </Helmet>

I tried making a different parent component only for this webpage but it seems like a lot of work.

1

There are 1 best solutions below

0
On

You can conditionally load the google tag manager script in Layout.jsx based on router.route (or maybe path or pathname since I'm using router from next/router, so router from react-router-dom's API might be a bit different but the general idea remains the same).

Let's say you want to disable it on page specific-tag, you can do:

import { useRouter } from 'next/router';

...

const router = useRouter();
const route = router.route;

return <Helmet>
      ...
    {route !== 'specific-tag' && <script
      async
      src="https://www.googletagmanager.com/gtag/js?id=G-{tag}"
    ></script>}
</Helmet>

Hope this helps!