22
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Reactで外部scriptを読み込むコンポーネント

Posted at

reactでscriptタグをrender中に書いても表示してくれない。

componentDidMountで手動でDOM操作すれば良さげ。
Reactで外部Scriptを動的に読み込む
Adding script tag to React/JSX

コンポーネント作るたびにDOM操作を書くのも面倒なので、scriptタグ設置用のコンポーネントクラスを定義

import {Component} from "react";
import React from "react";
import {PropTypes} from "prop-types";

const id = Math.random().toString();

class ScriptTag extends Component {
    componentDidMount() {
        const {src, async} = this.props;
        const script = document.createElement("script");

        script.src = src;
        script.async = async || false;

        document.getElementById(id).replaceWith(script)
    }

    render() {
        return <div id={id}/>
    }
}

ScriptTag.propTypes = {
    src: PropTypes.string.isRequired,
    async: PropTypes.bool
};

export default ScriptTag
22
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?