LoginSignup
2
2

More than 1 year has passed since last update.

[React] Componentの条件分岐をswitchを使わずに書く

Last updated at Posted at 2022-12-26

今までswitchを使ってこんな風に書いてた

const Pags : NextPage: () => {
  const { pageState } = useContext(PageStateContext);

  const TemplateComponent: FC = () => {
    switch(pageState) {
      case 'initial':
        return <InitialTemplate>;
      case 'confirm':
        return <ConfirmTemplate>;
      case 'complete':
        return <CompleteTemplate>;
      default:
        return <></>;
    }
  }

  return <TemplateComponent />;
}

今日教えてもらった書き方

const Pags : NextPage: () => {
  const { pageState } = useContext(PageState);

  return (
    {
      ['initial']: (<InitialTemplate />),
      ['confirm']: (<ConfirmTemplate />),
      ['complete']: (<CompleteTemplate />),
    }[pageState]
  );
}

疑問

これは、、文法的には何っていう書き方なんだろうか。。。

ソース

ここから取ってきたらしい。defaultの時の書き方も書いてある。

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