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

How to Add Script Tags to React Components?

Linda Hamilton
Release: 2024-12-09 09:14:06
Original
987 people have browsed it

How to Add Script Tags to React Components?

Adding Script Tag to React/JSX

In React, adding inline scripting to a component can be a straightforward task. To achieve this, consider the following options:

Conditional Rendering with Dynamic Code Injection:

import { Component } from 'react';

export default class extends Component {
    render() {
        if (process.env.NODE_ENV === 'production') {
            return (
                <script src="https://use.typekit.net/foobar.js" />
            );
        }

        return null;
    }
}
Copy after login

Dynamically Creating DOM Elements:

class Component extends React.Component {
    componentDidMount() {
        const script = document.createElement('script');

        script.src = 'https://use.typekit.net/foobar.js';
        script.async = true;

        document.body.appendChild(script);
    }

    render() {
        // ... Your component logic
    }
}
Copy after login

Using Hooks (useEffect with Cleanup):

import { useEffect, useRef } from 'react';

const useScript = (url) => {
  const ref = useRef(null);

  useEffect(() => {
    if (!ref.current) {
        const script = document.createElement('script');

        script.src = url;
        script.async = true;

        ref.current = script;
        document.body.appendChild(script);

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

Using Hooks (useEffect without Cleanup):

import { useEffect } from 'react';

const useScript = (url) => {
  useEffect(() => {
    const script = document.createElement('script');

    script.src = url;
    script.async = true;

    document.body.appendChild(script);
  }, [url]);
};
Copy after login

Note: It's generally recommended to use the first approach if you want to dynamically fetch and execute scripts during rendering, while the other approaches are suitable for loading scripts once when mounting the component into the DOM.

The above is the detailed content of How to Add Script Tags to React 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