islands/Counter.tsx
import type { Signal } from "@preact/signals";
import { Button } from "../components/Button.tsx";
interface CounterProps {
count: Signal<number>;
}
export default function Counter(props: CounterProps) {
return (
<div class="flex gap-8 py-6">
<Button onClick={() => props.count.value -= 1}>-1</Button>
<p class="text-3xl tabular-nums">{props.count}</p>
<Button onClick={() => props.count.value += 1}>+1</Button>
</div>
);
}
Fresh knows this file is an island because it lives in the /islands
directory. This means Fresh will render the file on the front end. It’ll ship the minimum amount of front-end JavaScript to handle just this “island” of interactivity. Then, it can be used in a variety of places, even by elements that are fully rendered on the server, where they can be optimized, pre-rendered, and shipped in a compact form. In theory, at least, this setup gives you the best of both worlds. Incorporating the island concept into file routing is a compelling idea.
If we return to the main index.tsx
file, you’ll see how the island is used:
/routes/index.tsx
import { useSignal } from "@preact/signals";
import Counter from "../islands/Counter.tsx";
export default function Home() {
const count = 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/logo.svg"
width="128"
height="128"
alt="the Fresh logo: a sliced lemon dripping with juice"
/>
<h1 class="text-4xl font-bold">Welcome to Fresh</h1>
<p class="my-4">
Try updating this message in the
<code class="mx-2">./routes/index.tsx</code> file, and refresh.
</p>
<Counter count={count} />
</div>
</div>
);
}
The main thing to notice here is the inclusion of the Counter
component (import Counter from "../islands/Counter.tsx"
) and its use in the normal JSX markup. This is a simple and direct means of combining server-side rendered code with front-end island functionality.