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
Release: 2024-12-09 04:48:10
Original
1023 people have browsed it

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);
}
Copy after login

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

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;
Copy after login

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
};
Copy after login

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!

source:php.cn
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