Intro to Deno Contemporary: A recent tackle full-stack JavaScript


islands/Counter.tsx 
import kind { Sign } from "@preact/indicators";
import { Button } from "../parts/Button.tsx";

interface CounterProps {
  depend: Sign<quantity>;
}

export default operate Counter(props: CounterProps) {
  return (
    <div class="flex gap-8 py-6">
      <Button onClick={() => props.depend.worth -= 1}>-1</Button>
      <p class="text-3xl tabular-nums">{props.depend}</p>
      <Button onClick={() => props.depend.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 quite a lot of locations, even by components which might be totally rendered on the server, the place they are often optimized, pre-rendered, and shipped in a compact kind. In idea, no less than, 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 House() {
  const depend = 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 Contemporary emblem: a sliced lemon dripping with juice"
        />
        <h1 class="text-4xl font-bold">Welcome to Contemporary</h1>
        <p class="my-4">
          Strive updating this message within the
          <code class="mx-2">./routes/index.tsx</code> file, and refresh.
        </p>
        <Counter depend={depend} />
      </div>
    </div>
  );
}

The primary factor to note right here is the inclusion of the Counter part (import Counter from "../islands/Counter.tsx") and its use within the regular JSX markup. It is a easy and direct means of mixing server-side rendered code with front-end island performance.

Leave a Reply

Your email address will not be published. Required fields are marked *