LoginSignup
6
5

More than 3 years have passed since last update.

scriptタグで書いたReactで外部ファイルのコンポーネントをimportしたい

Posted at

はじめに

公式Reactチュートリアルの「既存のウェブサイトにReactを追加する」というのがあります。
JavaScriptをscriptタグから読み込んで使うというReactの最もシンプルな使い方とあります。
このとき読み込まれるJavaScriptに使うコンポーネントを別ファイルから読み込ませたかったのですが、うまくいかなかったので、私の行った解決策をここにまとめたいと思います。

既存のウェブサイトにReactを追加する

解決策

手順を追って説明します。

1. scriptタグのtype属性にmoduleと書く

index.html
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>

    <div id="root"></div>

    <!-- CDNでReactを読み込む -->
    <script
      src="https://unpkg.com/react@16/umd/react.development.js"
      crossorigin
    ></script>
    <script
      src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
      crossorigin
    ></script>

    <!-- JSXをコンパイルしていない場合babelも読み込む必要があります -->




    <!-- ココです -->
    <script type="module" src="js/event-list.js"></script>

  </body>
</html>

2. コンポーネントのファイル

クラスを別ファイルに書き、エクスポートします。

LikeButton.js

class LikeButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = { liked: false };
  }

  render() {
    if (this.state.liked) {
      return "You liked this.";
    }

    return (
      <button
        onClick={() => {
          this.setState({ liked: true });
        }}
      >
        Like
      </button>
    );
  }
}

// クラスをexport
export default LikeButton;

3. importする

create-react-appで作ったReactアプリではimportするときの読み込み先のファイル名の拡張子「js」を省略できますが、この場合拡張子を省略してしまうと動きません。理由はよくわかりませんでしたが以下のようにすると動きました。

like-button.js

import LikeButton from "./LikeButton.js"; //読み込み元のファイル名の拡張子を省略しない

ReactDOM.render(
  <LikeButton />,
  document.getElementById("event-list-container")
);


おわりに

要するに、
「scriptタグのtype属性をmoduleとする」
「importするとき拡張子を省略しない」
ということです。
初心者が試行錯誤したやり方ですので、よりよい方法などありましたら教えていただけると嬉しいです。
間違い等もご指摘ください。
読んでいただきありがとうございました。

6
5
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
6
5