LoginSignup
75
58

More than 5 years have passed since last update.

ReactのJSXでifやforを使いたい場合

Posted at

JSPとかerbとかHTML系のテンプレートに慣れていると、
ReactのJSX内でifやforが使えないのがもどかしい事があると思います。

React的にはコンポーネントとして括り出すのがいいのは承知の上で、
ちょっと動作を確認したい時や、本当に大したことない処理の場合は
やはりインラインで書きたいものです。

以下のように即時関数を使えば実現できます。

export default class Header extends React.Component {
  render() {
    return <div className={s.root}>
      <div className={s.logo}>
        LOGO
      </div>

      {(() => {
        if (this.props.loggedIn)
          return <button style={{width:100}} onClick={this.onLogout.bind(this)}>
          Logout
        </button>;
      })()}
    </div>;
  }
}

これくらいシンプルな場合は、三項演算子使った方が読みやすいかも。

export default class Header extends React.Component {
  render() {
    return <div className={s.root}>
      <div className={s.logo}>
        LOGO
      </div>

      {(() => {
        return this.props.loggedIn ? <button style={{width:100}} onClick={this.onLogout.bind(this)}>
          Logout
        </button> : null;
      })()}
    </div>;
  }
}

参考:
https://facebook.github.io/react/tips/if-else-in-JSX.html

75
58
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
75
58