Closed8
[Astro] 条件式、ループ
HTMLの出力を条件式で制御したい。
公式ドキュメントではこれくらいしかサンプルがない。
---
const visible = true;
---
{visible && <p>表示!</p>}
{visible ? <p>表示!</p> : <p>あるいはこちらを表示!</p>}
---
const items = ["犬", "猫", "カモノハシ"];
---
<ul>
{items.map((item) => (
<li>{item}</li>
))}
</ul>
Astroテンプレートの構文はほぼJSXのようだ。
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つだけしか関数は書けない。
ifが使えれば複数条件も扱いやすい。
ループに三項演算子で条件をいれてみる。
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日前にクローズされました