Search code examples
javascriptreactjstracking

Add javascript object on componentDidMount in rendered html


I want to add a javascript object into the template when the component did mount for tracking purposes. The object needs to render out like this:

var tracking = {
        pagename: 'page name',
        channel: 'lp',
        subSection1: 'section',
        pageidentifier: 'identifier'
      }

I have set a state object the object in the componentDidMount function but I can't seem to get the object to appear on the page.

Below is what I have called in the render function which :

<script>{`
      var dataLayer = ${this.state.tracking}
    `}</script>

This returns [object,object] but I need it to write out the object.

How do I go about doing this? I can't find any examples of doing this and it seems like such a simple thing to do but can't figure it out


Solution

  • One way to append script tags is this:

    componentWillMount() {
            const script = document.createElement("script");
            script.text= this.state.tracking;    
            document.body.appendChild(script);
    }
    

    Though if this object is global, why not attach it straight to the window?
    window.dataLayer = this.state.tracking;