Alex Hyett
Alex Hyett

Alex Hyett

Adding Inline Javascript to a React App

Adding Inline Javascript to a React App

Alex Hyett's photo
Alex Hyett
·Feb 11, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

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=""
        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]"

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 = ''
        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

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

export default Giscus

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.

Share this