Search code examples
reactjsscript-tag

React update content of a script tag


I have the following script tag:

<script>
window.ac_vh_params = {
    containerId: 'container',
    folderName: '33/334'
};
</script>
<script src="https://somesdomain/main.js"></script>

My goal is to update and reload this script depend on a specific value, so I did the following:

import { useState, useEffect } from 'react';

const Demo = () => {
  const [selectedFolderName, setSelectedFolderName] = useState(null);

  useEffect(() => {
    if (!selectedFolderName) {
      return;
    }
    const container = document.getElementsByClassName('container')[0];
    container.innerHTML = '';
    const script1 = document.createElement('script');
    script1.text = `window.ac_vh_params = { containerId: 'container', folderName: '${selectedFolderName}' };`;
    container.appendChild(script1);
    const script2 = document.createElement('script');
    script2.src = 'https://somesdomain/main.js';
    container.appendChild(script2);
    return () => {
      container.removeChild(script1);
      container.removeChild(script2);
    }
  }, [selectedFolderName]);

  const handleClick = (e) => {
    const name = e.target.getAttribute('name') || e.currentTarget.getAttribute('name');
    setSelectedFolderName(name);
  };

  return (
    <div className="main">
      <button name="button1" onClick={handleClick}>Click 1</button>
      <button name="button2" onClick={handleClick}>Click 2</button>
      <div className="container">
      </div>
    </div>
  );
}

export default Demo;

The code changes as expected, but the new code not reloaded. How can I solve this? thanks.


Solution

  • Have you tried changing the parameters in the UseEffect itself? Something like

    useEffect(()=>{
    
    if (selectedFolderName) {
       window.ac_vh_params = { containerId: 'container', folderName: '${selectedFolderName}' };
        }
    }
    //... rest of code
    )