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

How to Safely Add Script Tags to React Components?

Barbara Streisand
Release: 2024-12-18 07:09:11
Original
224 people have browsed it

How to Safely Add Script Tags to React Components?

Adding Script Tag to React/JSX

In React, you can add inline scripting using either dangerouslySetInnerHTML or creating a script element in the componentDidMount lifecycle method.

Using dangerouslySetInnerHTML

allows you to specify raw HTML as a string, but it's important to note that it should be used with caution as it opens up security vulnerabilities. For instance:

<script src="https://use.typekit.net/foobar.js"></script>
<script dangerouslySetInnerHTML={{__html: 'try{Typekit.load({ async: true });}catch(e){}'}}></script>
Copy after login

However, this approach might not always execute the desired script.

Creating a Script Element in componentDidMount

Consider the following:

componentDidMount () {
    const script = document.createElement("script");

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

    document.body.appendChild(script);
}
Copy after login

This method dynamically inserts the script into the DOM when the component mounts.

Recommended Approach: Using npm Packages

Before using inline scripting, it's recommended to check if a pre-built npm package is available for the script you want to load. For instance, if you want to load Typekit, you can install the typekit package and import it like so:

import Typekit from 'typekit';
Copy after login

Update: Utilizing useEffect Hook

With the introduction of hooks, you can use useEffect to load scripts more efficiently:

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

You can also wrap this logic into a custom hook for easy reusability.

The above is the detailed content of How to Safely 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