How to include Script Tag and fetch data from it in React

How to include Script Tag and fetch data from it in React

With React functional components

There are certain use-cases where you want to include <script> tag directly in your react application, like using or including a particular third party library. Certain libraries are only available via CDN (<script> tag) for React as well, in such cases we have two ways either to include the <script> tag in index.html file in the public folder or to call in in useEffect (componentDidMount) block in your React application.

1. Putting it into index.html :

  • Go to index.html file in the public folder of the React project and add the script tag in the <head> section of your index.html file.

Screenshot 2022-10-16 at 10.47.45 PM.png

  • Point to be noted is that this tag will be loaded on all pages of your React Application.

2. Putting it in useEffect :

  • This method is effective when you need to call the <script> tag in a particular component of your application.

  • First create a function that can be called inside the useEffect.

const loadScript=()=>{
        window.NewScript=document.createElement('script');
        window.NewScript.src = 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/v4-shims.min.js';
        window.NewScript.id='third-party-script-async';
        document.body.appendChild(window.NewScript);
    }
  • Append the script source in the body of the DOM.

  • Assign id to the script for unique identification through getElementById.

  • Call the function inside the useEffect of your component.

useEffect(() => {
            if (document.getElementById("third-party-script-async") === null) {
             loadScript();
            }

            window.NewScript.onload = ()=> {
                console.log('calling onload');
                //perform additional manipulation of components
            }
   }, []);
  • In the window.onload() function you can try to pass params or do manipulation while the script has been loaded.

Conclusion

" useEffect " solution being efficacious and constructive is relatively recommended to be used, because the <script> tag will load only for the required component. In cases of using <script> tag for implying global settings like adding global fonts for entire application you can append the <script> tag in index.html file as shown in the first solution.