0
0

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 1 year has passed since last update.

【初心者】Reactを初めて使う私のためのメモ

Posted at

はじめに

フロントエンドエンジニアを目指して勉強中です。
アウトプットの場としてQiitaを活用しています。
プログラミング初心者のため、記事に間違いがあるかもしれません。
その際には、お手数ですがお知らせいただけると助かります。

本記事の概要

ドットインストールでReactの勉強中なので、気になって調べたところをまとめていきます。

ReactでHTMLを書く(Lesson #4)

1.前準備

まずはhtmlのファイルを作成。
headタグの中に、次のScriptを書くことで、npmを使わずにCDNからReactが使える(らしい)。

index.html
<head>
    <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>

ReactでコーディングしたJSXは、そのままではJavaScriptに変換されず、htmlで描画されないため、まずは、JavaScriptに変換してあげる必要があります。この変換(トランスパイル)にbabelが推奨されています。
bodyタグの中にReactを書くための準備として<script>タグを設置します。

index.html
<script type="text/babel">
</script>

2.レンダリング

<body>タグの中にidを付けた<div>タグを設置。
idを付与した<div>タグの中でレンダリングがされていきます。

index.html
<body>
    <div id="container"></div>
</body>

まずは、付与したidを取得し、レンダリングを行うためのコードを書きます。
React17までは、ReactDOM.createRoot()の部分が、ReactDOM.render()だったんだけど、React18からReactDOM.createRoot()とすることで並行処理ができるようになるとのこと。

index.html
<script type="text/babel">
    "use strict";
    {
        const container = document.querySelector("#container");
        const root = ReactDOM.createRoot(container);
        root.render();
    }
</script>

root.render():の()内にレンダリングしたいコードを書いていきます。
今回は、createElementを使っています。
createElementの参考:React入門チュートリアル (2) JSX

index.html
<script type="text/babel">
    "use strict";
    {
        const container = document.querySelector("#container");
        const root = ReactDOM.createRoot(container);
        root.render(React.createElement("h1", null, "menu"));
    }
</script>

これで、<h1>要素classなしのmenuという文字がレンダリングされているはずです。

以上が、基本的なレンダリングの方法となります。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?