1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【React】スプレッド構文でPropsを渡す際に、条件切り替えを行う方法

Posted at

まずこのような簡単な文字を表示する JSX を考える。

image.png

page.tsx
export default function Test() {
  const props = {
    style: {
      padding: '20px',
      color: 'red',
    },
  }

  return (
    <div {...props}>
      ラベル
    </div>
  )
}

このとき、何らかの変数によってスプレッド構文を渡したり渡さなかったりしたい。
そういう時は、スプレッド構文の中で切り替えるとよい。

page.tsx
  export default function Test() {
+   const isError = true

    const props = {
      style: {
        padding: '20px',
        color: 'red',
      },
    }

    return (
-     <div {...props}>
+     <div {...(isError && props)}>
        ラベル
      </div>
    )
  }

これに気付くのに少し時間がかかってしまった。
TSは 関数型 やこの && || を使いこなせるようになると楽しいね。

JSXHTML が思ったより TypeScript に寄せられてて感動している。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?