Island preact
설치
bun x astro add preact --yes
react와 비슷한 경량 라이브러리이다.
bun add @astrojs/preact@^5.1.2 preact@^10.29.1 가 추가됨.
astro.config.mjs 에 통합됨.
tsconfig.json 에 jsx 등록됨.
사용
- 확장자는 jsx 를 쓴다. preact 문법을 쓴다. (리엑트와 유사함)
- import { useState } from ‘preact/hooks’;
- 지시어가 존재한다. client:load , visible
예시
카운트버튼 컴포넌트
import { useState } from 'preact/hooks';
import '@styles/global.css';
export default function CountButton() {
const [count, setCount] = useState(0);
return (
<button class='btn' onClick={() => setCount(count + 1)}>{count}</button>
);
}
astro 에서 사용
---
import CountButton from '@/components/CountButton';
---
<CountButton client:load/>
Island Astro
소개
- 하나의 컴포넌트이다
- 디폴트로 파일명에 따라 내보내진다.
- 프런트메터 영역에서 서버 코드를 작성 할 수 있다.
- 스크립트 태그를 이용해서 클라이언트 코드를 작성 할 수 있다.Vanilla JS
- 서버 작업이 오래 걸릴때는 서버컴포넌트 로 지정해서 나중에 띄울 수 있다. (fallback 처리)
props 전달
---
const { title } = Astro.props;
---
- 컴포넌트에 속성을 선언하면 Astro.props 로 전달된다.
props 타입 지정
interface Props {
title: string;
}
- Props 타입을 선언하면 타입경고 및 오류를 표시한다.
slot
<div>
<slot/>
</div>
- slot 을 배치하면 컴포넌트의 자식요소를 받을 수 있다.
- 명명된 슬롯을 이용해서 여러개의 슬롯을 배치 할 수 있다.
예시
---
import FormattedDate from '@components/FormattedDate.astro';
interface Props{
title: string;
description: string;
pubDate: Date;
href: string;
}
const { title, description, pubDate, href } = Astro.props;
---
<style>
@reference "@styles/global.css";
.s_btn {
@apply cursor-pointer ;
}
</style>
<a href={href} class="s_btn text-base-content no-underline w-full shadow-xl bg-primary/10 rounded-2xl p-2">
<p class="font-bold border-b border-secondary/50 text-center">{title}</p>
<p>{description}</p>
<div class="text-end text-base-content/50 text-xs"><FormattedDate date={pubDate} /></div>
</a>
<script>
</script>