Adding script tag to React/JSX

2019-01-01 14:52发布

I have a relatively straightforward issue of trying to add inline scripting to a React component. What I have so far:

'use strict';

import '../../styles/pages/people.scss';

import React, { Component } from 'react';
import DocumentTitle from 'react-document-title';

import { prefix } from '../../core/util';

export default class extends Component {
    render() {
        return (
            <DocumentTitle title="People">
                <article className={[prefix('people'), prefix('people', 'index')].join(' ')}>
                    <h1 className="tk-brandon-grotesque">People</h1>

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

I have also tried:

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

Neither approach seems to execute the desired script. I'm guessing it's a simple thing I'm missing. Can anybody help out?

PS: Ignore the foobar, I have a real id actually in use that I didn't feel like sharing.

9条回答
栀子花@的思念
2楼-- · 2019-01-01 15:02

Further to the answers above you can do this:

import React from 'react';

export default class Test extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = true;
    s.innerHTML = "document.write('This is output by document.write()!')";
    this.instance.appendChild(s);
  }

  render() {
    return <div ref={el => (this.instance = el)} />;
  }
}

The div is bound to this and the script is injected into it.

Demo can be found on codesandbox.io

查看更多
后来的你喜欢了谁
3楼-- · 2019-01-01 15:07

Solution depends on scenario. Like in my case, I had to load a calendly embed inside a react component.

Calendly looks for a div and reads from it's data-url attribute and loads an iframe inside the said div.

It is all good when you first load the page: first, div with data-url is rendered. Then calendly script is added to body. Browser downloads and evaluates it and we all go home happy.

Problem comes when you navigate away and then come back into the page. This time the script is still in body and browser doesn't re-download & re-evaluate it.

Fix:

  1. On componentWillUnmount find and remove the script element. Then on re mount, repeat the above steps.
  2. Enter $.getScript. It is a nifty jquery helper that takes a script URI and a success callback. Once the script it loaded, it evaluates it and fires your success callback. All I have to do is in my componentDidMount $.getScript(url). My render method already has the calendly div. And it works smooth.
查看更多
低头抚发
4楼-- · 2019-01-01 15:10

If you need to have <script> block in SSR (server-side rendering), an approach with componentDidMount will not work.

You can use react-safe library instead. The code in React will be:

import Safe from "react-safe"

// in render 
<Safe.script src="https://use.typekit.net/foobar.js"></Safe.script>
<Safe.script>{
  `try{Typekit.load({ async: true });}catch(e){}`
}
</Safe.script>
查看更多
时光乱了年华
5楼-- · 2019-01-01 15:16

Do you want to fetch and execute the script again and again, every time this component is rendered, or just once when this component is mounted into the DOM?

Perhaps try something like this:

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

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

        document.body.appendChild(script);
    }

However, this is only really helpful if the script you want to load isn't available as a module/package. First, I would always:

  • Look for the package on npm
  • Download and install the package in my project (npm install typekit)
  • import the package where I need it (import Typekit from 'typekit';)

This is likely how you installed the packages react and react-document-title from your example, and there is a Typekit package available on npm.

查看更多
一个人的天荒地老
6楼-- · 2019-01-01 15:16

The answer Alex Mcmillan provided helped me the most but didn't quite work for a more complex script tag.

I slightly tweaked his answer to come up with a solution for a long tag with various functions that was additionally already setting "src".

(For my use case the script needed to live in head which is reflected here as well):

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

      const scriptText = document.createTextNode("complex script with functions i.e. everything that would go inside the script tags");

      script.appendChild(scriptText);
      document.head.appendChild(script);
  }
查看更多
皆成旧梦
7楼-- · 2019-01-01 15:21

There is a very nice workaround using Range.createContextualFragment.

/**
 * Like React's dangerouslySetInnerHTML, but also with JS evaluation.
 * Usage:
 *   <div ref={setDangerousHtml.bind(null, html)}/>
 */
function setDangerousHtml(html, el) {
    if(el === null) return;
    const range = document.createRange();
    range.selectNodeContents(el);
    range.deleteContents();
    el.appendChild(range.createContextualFragment(html));
}

This works for arbitrary HTML and also retains context information such as document.currentScript.

查看更多
登录 后发表回答