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 = "";
        scriptTag.async = true;

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 = "";
        scriptTag.async = true;

        return () => {
    }, []);

    return (
            Adding inline styles to functional component

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">
                    <script src="" type="text/javascript" />
export default AddingScriptExample;


Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.