3
2

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.

boolean による props の出し分けをシンプルに書く方法

Posted at

ニコニコ生放送でフロントエンドエンジニアをやっている @misuken です。

今回は何気に便利な tips の紹介です

React で props を組み立てる際、 boolean の条件によってオブジェクトの出し分けを行いたくなることがあります。

props だけでなく、構造化されたオブジェクトを組み立てるときに同じ場面に遭遇することは多いと思います。

例えば以下の型があったとして。

interface Props {
  required: { children?: React.ReactNode };
  optional?: { children?: React.ReactNode };
}

典型的な書き方

通常は三項演算子を使用して書きます。

const enabled = true;
const props: Props = {
  required: {
    children: "",
  },

  optional: enabled
    ? {
        children: "",
      }
    : undefined,
};

これだといろいろ面倒なことがあります。

  • ネストしている場合にインデントが深くなる
  • ネストしている場合に何を返しているかが読みづらく可読性が悪くなく
  • 条件の付け外し時に enabled ?: undefined の修正が必要で面倒
  • 条件の付け外し時にインデントが変化する
  • 条件の付け外し時に差分が二箇所に分かれる
  • 大きな props だと条件に一致しないときに返すものが把握しにくくなる

シンプルな書き方

(enabled || undefined) && を使うとシンプルに書けます。

const enabled = true;
const props: Props = {
  required: {
    children: "",
  },

  optional: (enabled || undefined) && {
    children: "",
  },
};

enabledfalse なら undefined が、 true ならオブジェクトが返ります。

条件の付け外しで変化する場所がまとまっていて、インデントも変化せず、大きな props でも可読性が落ちることがありません。

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?