Home >Web Front-end >JS Tutorial >How to Safely Add Script Tags to React Components?
In React, you can add inline scripting using either dangerouslySetInnerHTML or creating a script element in the componentDidMount lifecycle method.
<script src="https://use.typekit.net/foobar.js"></script> <script dangerouslySetInnerHTML={{__html: 'try{Typekit.load({ async: true });}catch(e){}'}}></script>
However, this approach might not always execute the desired script.
Consider the following:
componentDidMount () { const script = document.createElement("script"); script.src = "https://use.typekit.net/foobar.js"; script.async = true; document.body.appendChild(script); }
This method dynamically inserts the script into the DOM when the component mounts.
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';
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); } }, []);
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!