9
3

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.

React:JSX内でif文やswitch文を書きたい。

Posted at

JSX内で、三項演算子を使ってtrue、falseで表示したいものを変えるのはシンプルですが、選択肢が3つ以上の時はどうすればいいの?if文やswitch文を使いたい時はどうすればいいの?ということで調べてみました。

##解決方法##
アロー関数を使う。

colorがred、blue、green、defaultで表示を変えます。

colors関数を定義して、return内でcolors()関数を呼び出します。

import React from 'react'

const Card = ({ children, color }) => {
  const colors = () => {
    switch(color){
      case 'red':
        return(
        <div>
          <p>red</p>
          {children}
        </div>
      )
       case 'blue':
         return(
         <div>
          <p>blue</p>
          {children}
         </div>
      )
       case 'green':
        return(
        <div>
          <p>green</p>
          {children}
        </div>
      )
       default:
        return(
        <div>
          <p>default</p>
          {children}
        </div>
      )
    }
  }
  return (
    <>
    {colors()}
    </>
  )
}
export default Card
9
3
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
9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?