islands/Counter.tsx
import kind { Sign } from "@preact/indicators";
import { Button } from "../elements/Button.tsx";
interface CounterProps {
rely: Sign<quantity>;
}
export default operate 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>
);
}
Contemporary is aware of this file is an island as a result of it lives within the /islands
listing. This implies Contemporary 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 might be totally rendered on the server, the place they are often optimized, pre-rendered, and shipped in a compact kind. In idea, at the very least, 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 operate 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"
peak="128"
alt="the Contemporary emblem: a sliced lemon dripping with juice"
/>
<h1 class="text-4xl font-bold">Welcome to Contemporary</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.