メインコンテンツまでスキップ

Astro メモ

Props の渡し方

ファイルごとに渡す

Props の型付けは下記のように行う

---
interface Props {
name: string;
greeting?: string;
}

const { greeting = 'こんにちは', name } = Astro.props;
---

<h2>{greeting}, {name}</h2>



コンポーネント

astro 独自のファイルを作成する。また、JSX とかも使用できる



コンポーネントの子要素

<div>タグとかで囲わなくても渡せる

<slot>というタグで渡されたものを使う

---
// Wrapperコンポーネント
---
<div>
<slot />
</div>
---
// 子コンポーネント
import { Wrapper } from "../components/Wrapper.astro"
---
<Wrapper>
<button>子要素</button>
</Wrapper>


スタイル

MUI などのCSS-in-jsは使えない

なので、Tailwind などを使う必要がある



環境変数

下記の形式で.envファイルを読み込める

const host = import.meta.env.WP_HOST ?? "localhost";

ルーティング

src/pages配下のファイル名でルーティングされる

URL エンコード

何も工夫しない場合は日本語の URL は UTF-8 で渡されるので、動的ルート生成時にうまくいかない

なので、動的ルート生成の処理にデコード処理を入れる必要がある

---
// [slug].astro の [slug]に、WPで設定した記事のスラッグが対応します
const { slug } = Astro.params;

export async function getStaticPaths() {
const res = await fetch( WPURL + "/wp-json/wp/v2/posts");
const posts = await res.json();

return posts.map((post:any) => ({
params: { slug: decodeURI(post.slug) }, // <- ここにdecodeURI()を追加
props: { post: post },
}));
}
...