Adding Inline Javascript to a React App

Alex Hyett - Sep 26 '22 - - Dev Community

Let me start this with a disclaimer, I am not a React expert and I am sure there are probably other ways to do this. If you know of a better way then please let me know in the comments!

I have recently added Giscus to my blog which is a great way to add comments to a static developer blog.

I use Gatsby.js on my website which is built on React. The problem I had was working out how to add the Giscus script to my website.

This is what the Giscus script looks like.

<script src="https://giscus.app/client.js"
        data-repo="[ENTER REPO HERE]"
        data-repo-id="[ENTER REPO ID HERE]"
        data-category="[ENTER CATEGORY NAME HERE]"
        data-category-id="[ENTER CATEGORY ID HERE]"
        data-mapping="pathname"
        data-reactions-enabled="1"
        data-emit-metadata="0"
        data-input-position="bottom"
        data-theme="light"
        data-lang="en"
        crossorigin="anonymous"
        async>
</script>
Enter fullscreen mode Exit fullscreen mode

The script will load the comments wherever you place the script so it can’t be added to the header of your HTML file.

As you know with react it can’t just be added to your JSX as it is as it won’t compile. So I needed to change it to a React component that I could just import where I needed.

This is what I came up with for the Giscus component which works well for me:

import React, { Component } from 'react'

class Giscus extends Component {
    componentDidMount() {
        const script = document.createElement('script')
        script.src = 'https://giscus.app/client.js'
        script.dataset.repo = '[ENTER REPO HERE]'
        script.dataset.repoId = '[ENTER REPO ID HERE]'
        script.dataset.category = '[ENTER CATEGORY NAME HERE]'
        script.dataset.categoryId = '[ENTER CATEGORY ID HERE]'
        script.dataset.mapping = 'pathname'
        script.dataset.reactionsEnabled = '1'
        script.dataset.emitMetadata = '0'
        script.dataset.theme = 'light'
        script.dataset.lang = 'en'
        script.crossorigin = 'anonymous'
        script.async = true
        this.div.appendChild(script)
    }

    render() {
        return <div ref={(el) => (this.div = el)}></div>
    }
}

export default Giscus
Enter fullscreen mode Exit fullscreen mode

This approach should work for any other scripts that load components where the script is added to the HTML.

For general external javascript libraries, I would just add them to the HTML or use something like Helmet to add them where needed.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .