LoginSignup
8
6

More than 5 years have passed since last update.

JSX用の If文コンポーネントを作ったらすごく便利だった

Posted at

ReactのJSXには直接条件式を書くことはできないので、ある要素の表示を条件で切り替えるときには、埋め込み式の中で条件分岐を書かないといけません。

以下の例は、タブで表示画面を切り替える画面のために実装していたコードです。あまり見やすくありません。

{
  app.pageIs(5) ?
    (
      <div>
        <SupportMethodComponent app={app} support_method={data.support_method} />
        <StudentSupporterComponent app={app} student_supporter={data.student_supporter} />
      </div>
    ) : null
}

{
  app.pageIs(6) ?
    (
      <div>
        <StudentOtherActivityComponent app={app} other_activity={data.other_activity} />
        <PlanAfterGraduationComponent app={app} studying={data.studying} />
      </div>
    ) : null
}

他にいいやりかたがないか悩んでたんですが、表示を切り替えるためのIf文みたいに使えるコンポーネントを実装してみたところ、かなり見通しが良いコードに置き換えることができました。

以下が作ったコンポーネントです。

import React from 'react';

class IfComponent extends React.Component {
  render() {
    const {cond, children} = this.props;

    if (cond) {
      return (
        <div>
          {children}
        </div>
      );
    } else {
      return null;
    }
  }
}

IfComponent.propTypes = {
  cond: React.PropTypes.bool
};

export default IfComponent;

このコンポーネントを使って上のJSXを置き換えてみます。

<If cond={app.pageIs(5)}>
  <SupportMethodComponent app={app} support_method={data.support_method} />
  <StudentSupporterComponent app={app} student_supporter={data.student_supporter} />
</If>

<If cond={app.pageIs(6)}>
  <StudentOtherActivityComponent app={app} other_activity={data.other_activity} />
  <PlanAfterGraduationComponent app={app} studying={data.studying} />
</If>

かなり見通しが良くなりました。

単純なコンポーネントですがすごく便利です。
同じ問題でお悩みでしたら、ぜひ試してみてください。

8
6
1

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
8
6