Back on dry land. Take your blog from day to night, no island required!
이 컨텐츠는 아직 번역되지 않았습니다.
Now that you can build Astro islands for interactive elements, don’t forget that you can go pretty far with just vanilla JavaScript and CSS!
Let’s build a clickable icon to let your users toggle between light or dark mode using another <script> tag for interactivity… with no framework JavaScript sent to the browser.
요구 사항
Build an interactive theme toggle with only JavaScript and CSS
Send as little JavaScript to the browser as possible!
Add and style a theme toggle icon
Create a new file at src/components/ThemeIcon.astro and paste the following code into it:
Add the icon to Header.astro so that it will be displayed on all pages. Don’t forget to import the component.
Visit your browser preview at http://localhost:4321 to 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 theme
Choose some alternate colors to use in dark mode.
In global.css, define some dark styles. You can choose your own, or copy and paste:
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 <script> tag in src/components/ThemeIcon.astro after your <style> tag:
Check your browser preview at http://localhost:4321 and click the theme icon. Verify that you can change between light and dark modes.
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 client: to send their JavaScript to the client and run in the browser.
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.
They allow you to add interactivity without needing to know or learn any other JavaScript frameworks.