Build your first Astro island
This content is not available in your language yet.
Use a Preact component to greet your visitors with a randomly-selected welcome message!
Przygotuj się na…
- Add Preact to your Astro project
- Include Astro islands (Preact
.jsx
components) on your home page - Use
client:
directives to make islands interactive
Add Preact to your Astro project
Section titled Add Preact to your Astro project-
If it’s running, quit the dev server to have access to the terminal (keyboard shortcut: Ctrl + C).
-
Add the ability to use Preact components in your Astro project with a single command:
-
Follow the command line instructions to confirm adding Preact to your project.
Include a Preact greeting banner
Section titled Include a Preact greeting bannerThis component will take an array of greeting messages as a prop and randomly select one of them to show as a welcome message. The user can click a button to get a new random message.
-
Create a new file in
src/components/
namedGreeting.jsx
Note the
.jsx
file extension. This file will be written in Preact, not Astro. -
Add the following code to
Greeting.jsx
: -
Import and use this component on your Home page
index.astro
.Check the preview in your browser: you should see a random greeting, but the button won’t work!
-
Add a second
<Greeting />
component with theclient:load
directive. -
Revisit your page and compare the two components. The second button works because the
client:load
directive tells Astro to send and rerun its JavaScript on the client when the page loads, making the component interactive. This is called a hydrated component. -
Once the difference is clear, remove the non-hydrated Greeting component.
Analyze the Pattern
Section titled Analyze the PatternThere are other client:
directives to explore. Each sends the JavaScript to the client at a different time. client:visible
, for example, will only send the component’s JavaScript when it is visible on the page.
Consider an Astro component with the following code:
-
Which of the five components will be hydrated islands, sending JavaScript to the client?
-
In what way(s) will the two
<PreactBanner />
components be the same? In what way(s) will they be different? -
Assume the
SvelteCounter
component shows a number and has a button to increase it. If you couldn’t see your website’s code, only the live published page, how would you tell which of the two<SvelteCounter />
components usedclient:visible
?
Test your knowledge
Section titled Test your knowledgeFor each of the following components, identify what will be sent to the browser:
-
<ReactCounter client:load />
-
<SvelteCard />