Home  Reactjs   How to exec ...

How to execute code after the script is loaded in react

const BasicContactForm = () => { useEffect(() => { const scriptId = "turnstile-script";

// Function to load the script
const loadScript = () => {
  return new Promise((resolve, reject) => {
    if (document.getElementById(scriptId)) {
      resolve();
      return;
    }

    const script = document.createElement("script");
    script.id = scriptId;
    script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
    script.async = true;
    script.defer = true;
    script.onload = () => resolve();
    script.onerror = (err) => reject(err);
    document.head.appendChild(script);
  });
};

const loadAndRenderTurnstile = async () => {
  try {
    await loadScript();

    console.log("Turnstile rendered and loaded");
  } catch (error) {
    console.error("Failed to load Turnstile script:", error);
  }
};

//code to run after script is loaded

loadAndRenderTurnstile();

return () => {
  // Remove the script when the component is unmounted
  const script = document.getElementById(scriptId);
  if (script) {
    script.remove();
  }
};

},[]);

return ( <form className="md:w-1/2 flex-grow"

  role="form"
  id="f1"
  name="f1"
>
  <h1 className="text-center text-primary">Contact Me!</h1>
</form>

); };

export default BasicContactForm;

Published on: Aug 08, 2024, 04:53 AM  
 

Comments

Add your comment