6 • Set sail for Astro islands
Back on dry land. Take your blog from day to night, no island required!
Let’s build a clickable icon to let your users toggle between light or dark mode using another
Get ready to…
Add and style a theme toggle iconSection titled Add and style a theme toggle icon
Create a new file at
src/components/ThemeIcon.astroand paste the following code into it:
Add the icon to
Header.astroso that it will be displayed on all pages. Don’t forget to import the component.
Visit your browser preview at
localhost:3000to see the icon now on all your pages. You can try clicking it, but you have not written a script to make it interactive yet.
Add CSS styling for a dark themeSection titled Add CSS styling for a dark theme
Choose some alternate colors to use in dark mode.
global.css, define some dark styles. You can choose your own, or copy and paste:
Add client-side interactivitySection titled Add client-side interactivity
To add interactivity to an Astro component, you can use a
<script> tag. This script can check and set the current theme from
localStorage and toggle the theme when the icon is clicked.
Add the following
Check your browser preview at
localhost:3000and click the theme icon. Verify that you can change between light and dark modes.
Test your knowledgeSection titled Test your knowledge
Choose whether each of the following statements describes Astro
<script> tags, UI framework components, or both.
They allow you to include interactive UI elements on your website.
They will create static elements on your site unless you include a
They allow you to “try out” a new framework without requiring you to start an entirely new project using that tech stack.
They allow you to reuse code you have written in other frameworks and you can often just drop them right into your site.