Home > Web Front-end > JS Tutorial > How to Safely and Efficiently Add Script Tags to React Components?

How to Safely and Efficiently Add Script Tags to React Components?

Mary-Kate Olsen
Release: 2024-12-20 04:22:13
Original
491 people have browsed it

How to Safely and Efficiently Add Script Tags to React Components?

Adding Script Tag to React/JSX

The goal of this question is to explore methods for adding inline scripting to React components. The user has attempted to load an external script using both inline script tags and the dangerouslySetInnerHTML property, but neither approach seems to execute the desired script.

One solution suggested is to create a componentDidMount method in the React component and dynamically create and append a script element to the DOM. This approach ensures that the script is executed only once when the component is mounted.

However, a more modern and recommended approach in React is to use the useEffect hook. This hook allows you to perform side effects, such as making API calls or manipulating the DOM, after the component has rendered.

The following code snippet demonstrates how to use useEffect to load a script:

useEffect(() => {
  const script = document.createElement('script');
  script.src = 'https://use.typekit.net/foobar.js';
  script.async = true;
  document.body.appendChild(script);

  return () => {
    document.body.removeChild(script);
  }
}, []);
Copy after login

By wrapping this code in a custom hook, it becomes reusable in multiple components:

const useScript = url => {
  useEffect(() => {
    const script = document.createElement('script');
    script.src = url;
    script.async = true;
    document.body.appendChild(script);

    return () => {
      document.body.removeChild(script);
    }
  }, [url]);
};
Copy after login

Which can be used as follows:

import useScript from 'hooks/useScript';

const MyComponent = props => {
  useScript('https://use.typekit.net/foobar.js');

  // Rest of the component
}
Copy after login

Utilizing the useEffect hook with a custom script hook provides a clean and efficient way to load and execute scripts in React components.

The above is the detailed content of How to Safely and Efficiently Add Script Tags to React Components?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template