Closed8

[Astro] 条件式、ループ

平田直毅平田直毅

HTMLの出力を条件式で制御したい。
公式ドキュメントではこれくらいしかサンプルがない。

https://docs.astro.build/ja/basics/astro-syntax/#動的html

---
const visible = true;
---
{visible && <p>表示!</p>}

{visible ? <p>表示!</p> : <p>あるいはこちらを表示!</p>}
---
const items = ["犬", "猫", "カモノハシ"];
---
<ul>
  {items.map((item) => (
    <li>{item}</li>
  ))}
</ul>
平田直毅平田直毅

ifを使いたい場合は、関数にしてreturnすればいい。

const isMorning = true
const name="太郎"
---
{
  () => {
    if (isMorning){
      return <div>{name}, Good morning!</div>
    } else {
      return <div>{name}, Good evening!</div>
    }
  }
}
太郎, Good morning!

{} 内には1つだけしか関数は書けない。

平田直毅平田直毅

ループに三項演算子で条件をいれてみる。

const fruits = ["apple", "orange", "banana", "peach"]
---
{
  fruits.map((fruit) =>
    fruit === "apple" ?
      <div>apple get!</div>
    : fruit === "orange" || fruit === "peach" ?
      <div>orange or peach found!</div>
    : <div>{fruit}</div>
  )
}
apple get!
orange or peach found!
banana
orange or peach found!

読みにくい。

平田直毅平田直毅

ifを使った方が読みやすい。ただしreturnで返すタグが大きくなれば読みづらくなる。

const fruits = ["apple", "orange", "banana", "peach"]
---
{
  fruits.map((fruit) => {
    if (fruit === "banana"){
      return <div>banana found!</div>
    } else {
      return <div>{fruit}</div>
    }
  })
}
apple
orange
banana found!
peach
平田直毅平田直毅

タグにしたくない場合はフラグメントを使う。

const fruits = ["apple", "orange", "banana", "peach"]
---
{
  fruits.map((fruit) => {
    return <>{fruit}</>
  })
}
appleorangebananapeach
平田直毅平田直毅

多重ループ

const favCities = [
  { country: "USA", cities: ["New York", "San Francisco"] },
  { country: "Spain", cities: ["Madrid", "Barcelona"] },
  { country: "Japan", cities: ["Tokyo"] },
  { country: "Germany", cities: ["Berlin"] }
]
---
{
  favCities.map((countryData) => ( 
    <>
      <ul>
        {
          countryData.cities.map((city) => <li>{city}</li>)
        }
      </ul>
    </>
  ))
}
USA
  New York
  San Francisco
Spain
  Madrid
  Barcelona
Japan
  Tokyo
Germany
  Berlin
このスクラップは4日前にクローズされました