How to add script or inline tag to react component


Sometimes, We want to add the script tag to individual components. This post talks about adding script or inline scripts to individual components multiple approaches

  • Functional components with useHook
  • React class components with componentWillMount
  • React-helmet npm package

how to add script tag to react components

This section describes adding script tag to class and functional components.

React class components

There is a call back method componentWillMount which will be called for every render of an react component. Inside call back,

  • Created script tag using document createElement function which creates script tag
  • Change created script tag attributes src and async
  • Finally add script tag to document.body or document.head

Example code:

   componentWillMount() {
        const scriptTag = document.createElement("script");
        scriptTag.src = "https://use.typekit.net/hello.js";
        scriptTag.async = true;
        document.body.appendChild(scriptTag);
    }

The same code can be replaced with functional components using useEffect() hook. useEffect hookes calls for every render of an react component,

if you pass an empty array to return inside useEffect() hook, It will load and run only once.

import React from 'react';
import { useEffect } from 'react';

function InlineStyleComponent(props) {

    useEffect(() => {
        const scriptTag = document.createElement('script');

        scriptTag.src = "https://use.typekit.net/foobar.js";
        scriptTag.async = true;

        document.body.appendChild(scriptTag);
        return () => {
            document.body.removeChild(scriptTag);
        }
    }, []);

    return (
        <div>
            Adding inline styles to functional component
        </div>
    );
}

export default InlineStyleComponent;

react-helmet adding script tag inside head tag

React helmet is an npm library which manages browser head manager, It is very easy to change web page lines of code inside a head tag.

First install react-helment with npm install command

npm install react-helmet

It adds dependency to package.json

"dependencies": {
        "react-helmet": "^6.1.0",
}

Complete component code to add script tag to component using react-helment.

import React, { Component } from 'react';
import { Helmet } from 'react-helmet';

class AddingScriptExample extends Component {


    render() {
        return (
            <div className="application">
                <Helmet>
                    <script src="https://use.typekit.net/hello.js" type="text/javascript" />
                </Helmet>
            ...
            </div>
        );
    }
}
export default AddingScriptExample;

Wrap

Similar Posts