islands/Counter.tsx
import kind { Sign } from "@preact/indicators";
import { Button } from "../parts/Button.tsx";
interface CounterProps {
rely: Sign<quantity>;
}
export default perform Counter(props: CounterProps) {
return (
<div class="flex gap-8 py-6">
<Button onClick={() => props.rely.worth -= 1}>-1</Button>
<p class="text-3xl tabular-nums">{props.rely}</p>
<Button onClick={() => props.rely.worth += 1}>+1</Button>
</div>
);
}
Recent is aware of this file is an island as a result of it lives within the /islands
listing. This implies Recent will render the file on the entrance finish. It’ll ship the minimal quantity of front-end JavaScript to deal with simply this “island” of interactivity. Then, it may be utilized in a wide range of locations, even by parts which can be totally rendered on the server, the place they are often optimized, pre-rendered, and shipped in a compact type. In idea, a minimum of, this setup provides you the very best of each worlds. Incorporating the island idea into file routing is a compelling thought.
If we return to the primary index.tsx
file, you’ll see how the island is used:
/routes/index.tsx
import { useSignal } from "@preact/indicators";
import Counter from "../islands/Counter.tsx";
export default perform Dwelling() {
const rely = useSignal(3);
return (
<div class="px-4 py-8 mx-auto bg-[#86efac]">
<div class="max-w-screen-md mx-auto flex flex-col items-center justify-center">
<img
class="my-6"
src="https://www.infoworld.com/emblem.svg"
width="128"
top="128"
alt="the Recent emblem: a sliced lemon dripping with juice"
/>
<h1 class="text-4xl font-bold">Welcome to Recent</h1>
<p class="my-4">
Attempt updating this message within the
<code class="mx-2">./routes/index.tsx</code> file, and refresh.
</p>
<Counter rely={rely} />
</div>
</div>
);
}
The primary factor to note right here is the inclusion of the Counter
element (import Counter from "../islands/Counter.tsx"
) and its use within the regular JSX markup. This can be a easy and direct means of mixing server-side rendered code with front-end island performance.