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

How to Efficiently Add Script Tags to React/JSX Components?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-09 04:48:101024browse

How to Efficiently Add Script Tags to React/JSX Components?

Adding Script Tag to React/JSX

In React/JSX, there are several approaches to incorporate inline scripting. One potential solution is to create a function within the component that mounts the script into the DOM. For instance:

componentDidMount() {
  const script = document.createElement("script");
  script.src = "https://use.typekit.net/foobar.js";
  script.async = true;
  document.body.appendChild(script);
}

However, this method is not ideal if the script already exists in the DOM or needs to be loaded multiple times.

A more effective approach is to leverage a package manager like npm to install the script as a module. This simplifies the integration process and makes the script accessible for import:

import {useEffect} from 'react';

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);
  };
}, []);

This technique ensures that the script is loaded only once when the component mounts and is removed when the component unmounts.

To further enhance this approach, a custom hook can be created to handle the script loading process:

import { useEffect } from 'react';

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]);
};

export default useScript;

This custom hook can then be utilized in any component that requires the script:

import useScript from 'hooks/useScript';

const MyComponent = props => {
  useScript('https://use.typekit.net/foobar.js');
  // Rest of the component code
};

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

Statement:
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