5

I'm trying to add Google Analytics to my site with the following react-helmet:

         <Helmet
              htmlAttributes={{
                lang: this.props.language
                  ? convertLangCodeToISO639(this.props.language)
                  : "en",
              }}
            >
              {this.props.googleTrackingID && (
                <>
                  <script
                    async
                    src={`https://www.googletagmanager.com/gtag/js?id=${this.props.googleTrackingID}`}
                  ></script>
                  <script>
                    {`window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', \"${this.props.googleTrackingID}\");`}
                  </script>
                </>
              )}
            </Helmet>

Unfortunately this gives the error:

TypeError: Cannot convert a Symbol value to a string. Helmet does not support rendering <" + child.type + "> elements. Refer to our API for more information.

This isn't what I am doing since I am using <script> tags. I also need the outer JSX tag since there are two child <script> tags.

What is causing this error?

David Ferris
  • 2,215
  • 6
  • 28
  • 53

1 Answers1

10

I was eventually able to do this with multiple <Helmet> tags, moving the JSX conditional outside helmet:

         <Helmet
              htmlAttributes={{
                lang: this.props.language
                  ? convertLangCodeToISO639(this.props.language)
                  : "en",
              }}
            />
            {/*  Google Analytics */}
            {this.props.survey.googleTrackingID && (
              <Helmet>
                <script
                  async
                  src={`https://www.googletagmanager.com/gtag/js?id=${this.props.survey.googleTrackingID}`}
                ></script>
                <script>
                  {`window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', "${this.props.survey.googleTrackingID}");`}
                </script>
              </Helmet>
            )}
David Ferris
  • 2,215
  • 6
  • 28
  • 53