islands/Counter.tsx
import type { Signal } from “@preact/signals”;
import { Button } from “../components/Button.tsx”;
interface CounterProps {
count: Signal;
}
export default function Counter(props: CounterProps) {
return (
props.count.value -= 1}>-1
{props.count}
props.count.value += 1}>+1
);
}
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 (
Try updating this message in the
./routes/index.tsx file, and refresh.
);
}
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.