naopoyo.com
  • Docs
  • Tags
  • Bookmarks
  • Tools
  • About
  • Docs
  • Tags
  • Bookmarks
  • Tools
  • About

目次

© naopoyo

🔨

next-themesとshadcn/uiのToggle Groupを使ってTheme Switcherを作った

公開日
1年以上前
2024-07-27
更新履歴
GitHubで見る
  • shadcn/ui
  • next-themes
preview

作成したTheme Switcher

画像のようなTheme Switcherを作成しました。shadcn/uiのToggle Groupとnext-themesを使って、最小限のスタイル調整でNext.jsの公式サイトで使われているものと同じような見た目を再現しています。

次のコードをNext.jsで使ってみてください。

Theme Switcherのコード
src/components/theme-switcher.tsx
'use client'

import { ComputerIcon, MoonIcon, SunIcon } from 'lucide-react'
import { useTheme } from 'next-themes'
import { useEffect, useState } from 'react'

import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group'

export default function ThemeSwitcher() {
  const [mounted, setMounted] = useState(false)
  const { theme, setTheme } = useTheme()

  useEffect(() => {
    setMounted(true)
  }, [])

  if (!mounted || theme === undefined) {
    return
  }

  return (
    <ToggleGroup
      className='rounded-full border p-1'
      size='sm'
      type='single'
      value={theme}
      onValueChange={(value) => setTheme(value)}
    >
      <ToggleGroupItem className='rounded-full' value='dark' aria-label='Toggle dark'>
        <MoonIcon size={16} />
      </ToggleGroupItem>
      <ToggleGroupItem className='rounded-full' value='system' aria-label='Toggle system'>
        <ComputerIcon size={16} />
      </ToggleGroupItem>
      <ToggleGroupItem className='rounded-full' value='light' aria-label='Toggle light'>
        <SunIcon size={16} />
      </ToggleGroupItem>
    </ToggleGroup>
  )
}

ThemeSwitcherを使用する方法

上記のThemeSwitcherを使用するためには、次のドキュメントの通りに必要なパッケージを追加していく必要があります。

  1. shadcn/uiをインストール

    Next.js
    Install and configure shadcn/ui for Next.js.
    shadcn.com favicon
    shadcn.com
    Next.js
  2. ダークモードの設定

    Next.js
    Adding dark mode to your next app.
    shadcn.com favicon
    shadcn.com
    Next.js
  3. Toggle Groupを追加

    Terminal
    pnpm dlx shadcn-ui@latest add toggle-group

目次

最近更新された記事

🛷
開発日記-2025-10-29 / tocbot のオプション
1日前 - 2025年10月29日
  • 開発日記
  • tocbot
🚩
Next.js 16にアップグレードする
2日前 - 2025年10月27日
  • Next.js
✒️
エンジニア個人ブログまとめ
3日前 - 2025年10月27日
  • デザイン
  • Next.js
  • Markdown