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.

JSX記法のルール

0
Posted at

はじめに

Reactを実装するために使用するJSX記法の基本ルールについてアウトプットします.

JSX記法とは

JSXとはJavaScript XMLの略で,Reactを実装するためのJavaScript拡張構文.JSXはJavaScriptの中にHTMLとほとんど同じように記述することができるため,UIを簡単に記述し,視覚的に理解しやすい.

基本ルール

Reactで共通の記述

index.js
import React from 'react';
import ReactDOM from 'react-dom/client';

//ここに画面の要素を書いていく

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

npx create-react-app ディレクトリ名コマンドで,上のようなindex.jsが自動で生成されるため,自分で書くことはほとんどない.

コンポーネントの作成

Reactは画面の要素をJavaScriptの関数で表す.この関数を コンポーネント と呼ぶ.コンポーネントは,大文字始まりで記述する.
画面に表示したい要素を,関数の結果としてreturnすることで,画面に要素を表示する.

index.js
import React from 'react';
import ReactDOM from 'react-dom/client';

const App = () => {
  return <h1>こんにちは</h1>
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

注意

return内で複数行の要素を返すときは,()で囲う必要がある.
また,return内は一つのタグで囲う必要がある.divタグなどで囲ってもよいが,囲わないことによるエラーを回避するために用意されたflagment(空タグ)<>を使用することもできる.

index.js
・・・

const App = () => {
  return (
    <>
      <h1>こんにちは</h1>
      <h1>はじめまして</h1>
    </>
  );
}

・・・
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?