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 3 years have passed since last update.

【React②】JSX

Last updated at Posted at 2020-10-22

JSXとは

XMLのようなタグを記述できるJavaScriptの拡張言語。これを使えば、短く直感的にわかりやすい記述ができる。
JSXはBabelによって暗黙的にJavaScriptに変換される。
以下のページの左側にXMLを入力すると、右側にリアルタイムでJavaScriptが表示されることが確認できる。
https://babeljs.io/

使い方

import React, { Component } from 'react';

するだけ。他には

  • 変数キャメルケースで書く
  • コンポネントには閉じタグ/>が必要

例えば、https://babeljs.io/ に以下のコードをかくと、

class App extends Component{
  render(){
    return <div>Foo</div>;
  }
}

暗黙的にBabbleが以下のようにReact.createElement()に変換してくれるのです。
HTMLのように、最終形に近い形で記述できることになります👏

function render() {
  return React.createElement('div', null, 'Foo');
}

式をうめこむ

JSXを使えば、JavaScriptの式をJSX内で中括弧に囲んで使用できます。

const name = 'Tom';
const element = <h1>Hello, {name}</h1>;

ReactDOM.render(
  element,
  document.getElementById('root')
);

属性を指定

JSXではclass属性の指定はclassではなくclassNameで指定する。
例えば下の例だと、h1タグがトランスパイルされてdomという変数に代入されている。

class App extends Component{
  render(){ 
    const greeting = "Hi, Tom!";
    const dom = <h1 className="foo"> {greeting}</h1>;  
    return dom;
  }
}

タグの属性

HTMLタグの属性forはReactではhtmlForで指定できる。labelに付与することで、同じ内容のid属性を持つ要素と関連付ける。
下の例ではonChangeベントハンドラによりformへの入力が変化するとI am clickedが表示される。

class App extends Component{
  render(){ 
    return(
      <div>
         <label htmlFor="bar">bar</label>
         <input type="text" onChange={() => {console.log("I am clicked.")}}/>
          //条件がクリックの場合はonClick
      </div>
    )
  }
}

また、Reactのreturn内で返すタグは1個でないといけない。

//エラー文
index.js: Adjacent JSX elements must be wrapped in an enclosing tag

そこでreturn内を<div>で囲って対応、、、
するとReactのための意図せぬタグが増えてしまうので、<React.Fragment>が用意されている。
<div>ではなく、<React.Fragment>で囲うことで、最終的に画面に表示されるHTMLに余計なタグが出力されない。
<React.Fragment> ではkey={item.id}も指定可能。

class Columns extends React.Component {
  render() {
    return (
      <React.Fragment>
        <td>Hello</td>
        <td>World</td>
      </React.Fragment>
    );
  }
}

以下のように<></>を使って単略化して書くこともできるが、key属性は指定できない。

class Columns extends React.Component {
  render() {
    return (
      <>
        <td>Hello</td>
        <td>World</td>
      </>
    );
  }
}

比較

JSXを使わずReactを使ってDOMを描画すると、こんな感じに長くなる。

 class App extends Component {
   render() {
     return React.createElement(
       "div",
        null,
       "Hello, world!!"
     );
   }
 }
export default App;
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?