LoginSignup
236
219

More than 5 years have passed since last update.

Stateless な React Component の記法をまとめてみた

Last updated at Posted at 2016-06-22

はじめに

React Component には様々な書き方があるので、自分の理解のため整理してみました。

var CommentBox = ...

ReactDOM.render(
  <CommentBox hello="Hello, world" name="CommentBox" />,
  document.getElementById('content')
)

以下、CommentBox に hello と name という props を渡す stateless なコンポーネントを前提とします。

基本型

チュートリアルに出てくる書き方で、誰しもが真っ先に覚える書き方かと思います。
https://facebook.github.io/react/docs/tutorial.html

var CommentBox = React.createClass({
  render: function() {
    return (
      <div className="commentBox">
        {this.props.hello}! I am a {this.props.name}.
      </div>
    );
  }
});

ES6 Class

ES6のclassを利用する方法です。
https://facebook.github.io/react/docs/reusable-components.html

class CommentBox extends React.Component {
  constructor(props) {
    super(props)
  }
  render() {
    return (
      <div className="commentBox">
        {this.props.hello}! I am a {this.props.name}.
      </div>
    );
  }
}

propsをそのまま渡すだけなら、constructorを定義しなくとも構いません。

class CommentBox extends React.Component {
  render() {
    return (
      <div className="commentBox">
        {this.props.hello}! I am a {this.props.name}.
      </div>
    );
  }
}

Stateless Functions

実は、プレーンなJavascript関数でもOKです。

function CommentBox(props) {
  return(
    <div className="commentBox">
      {props.hello}! I am a {props.name}.
    </div>
  )
}

ES6のarrow syntaxを使うと、以下のように書けます。

const CommentBox = (props) => {
  return(
    <div className="commentBox">
      {props.hello}! I am a {props.name}.
    </div>
  )
}

propsを展開してもよいです。

const CommentBox = ({hello, name}) => {
  return(
    <div className="commentBox">
      {hello}! I am a {name}.
    </div>
  )
}

arrow function で 右辺に expression を書けることを利用すると、さらに短く書けます。

const CommentBox = ({hello, name}) => (
  <div className="commentBox">
    {hello}! I am a {name}.
  </div>
)

で、どの書き方がいいの?

https://facebook.github.io/react/docs/reusable-components.html

末尾に

In an ideal world, most of your components would be stateless functions because in the future we’ll also be able to make performance optimizations specific to these components by avoiding unnecessary checks and memory allocations. This is the recommended pattern, when possible.

と書かれています。
この指針に素直に従い、可能なら Statless Functions で書くのがよさそうです。

最終形

propTypesまで含めるとこんな形になるかと。

import React from 'react'

const App = ({hello, name}) => (
  <div className="commentBox">
    {hello}! I am a {name}.
  </div>
)

App.propTypes = {
  hello: React.PropTypes.string.isRequired,
  name: React.PropTypes.string.isRequired
}
236
219
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
236
219