Skip to main content
  1. Posts/

Day 26 - Animate UI Theme Toggler

·183 words·1 min· loading · loading · ·
ADSFAaron
Author
ADSFAaron
Table of Contents
Animate UI Series - This article is part of a series.
Part 26: This Article

前言
#

先祝福大家雙十快樂 😆 又一個快樂的三天連假要放啦~

今天要來介紹的是 Animate UI 1.0 更新後的新元件 – Theme Toggler,與 Day 4 所介紹的 Dark Mode 非常類似,但是多了一點動畫,讓深淺色模式在切換時感覺更高級 🌝

Theme Toggler
#

Theme toggler Demo 1

  1. 使用 Shadcn CLI 加入 Theme Toggler

    npx shadcn@latest add @animate-ui/components-buttons-theme-toggler
    
  2. 深色模式安裝請參考 Day4 - Dark Mode

  3. Import 元件並將元件放在想要的位置上

    import {
        ThemeTogglerButton,
        type ThemeTogglerButtonProps,
    } from '@/components/animate-ui/components/buttons/theme-toggler';
    
    const { theme, setTheme } = useTheme();
    const hasSystemMode = true;    // 若沒有系統模式,則不顯示系統模式按鈕
    
    <ThemeTogglerButton
        modes={hasSystemMode ? ['light', 'dark', 'system'] : ['light', 'dark']}
    />
    
  4. 這時你可能會出現錯誤,少了 @/lib/get-strict-context 檔案

    Theme toggler Error

    這時請至 Animate UI Github Repo 複製這個檔案至 /util 目錄下,並且命名為 get-strict-context.tsx

    Theme toggler Solve

    Theme toggler Solve Path

  5. 若還有想要微調,可以增加更多參數 (? 表示為選填參數)

    ThemeTogglerButtonProps
    #

    參數 參數型態 說明
    variant string 按鈕外觀樣式,有 "default" | "accent" | "destructive" | "outline" | "secondary" | "ghost" | "link",預設為 'default'
    size string 按鈕尺寸,可調整為 'default''sm''lg',預設為 'default'
    modes string[] 可切換的主題模式,預設為 ['light', 'dark', 'system']
    direction 'ltr' | 'rtl' | 'btt' | 'ttb' 主題切換方向(l = left, r = right, t = top, b = bottom),預設為 'ltr'
    onImmediateChange (mode: string) => void 主題切換時觸發的函式
    onClick (event: MouseEvent) => void 點擊按鈕時觸發的事件
    className string 自訂按鈕樣式的 class 名稱,可參考 Tailwind CSS

小結
#

冷知識

今年十月上班日跟十一月的上班日是一樣多的哦 🤪

這次介紹的 Animate UI – Theme Toggler,不只是單純的「亮/暗模式切換鈕」,更像是網站氣氛的調光師,並且一步步了解如何透過 shadcn cli 安裝、調整各種參數,以及實際踩到的坑與修正方式,讓整個切換流程更順暢、更聰明。

無論你想打造沉穩的深夜模式,還是陽光灑落的白天風格,Theme Toggler 都能幫你輕鬆掌握整體視覺節奏 🎨。

Reference
#

Animate UI Series - This article is part of a series.
Part 26: This Article