From 3bd926d1620e1583adc6b83261311e623edaf898 Mon Sep 17 00:00:00 2001 From: Bochkovskyi Date: Fri, 29 Sep 2023 21:12:45 +0300 Subject: [PATCH] add theme toggle functionality --- package-lock.json | 13 ++++++++++++- package.json | 1 + src/app/layout.jsx | 7 +++++-- src/app/page.jsx | 23 +++++++++++++++++++++++ 4 files changed, 41 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index b66c243..d86709a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19,6 +19,7 @@ "autoprefixer": "^10.4.15", "husky": "^8.0.3", "lint-staged": "^14.0.1", + "next-themes": "^0.2.1", "postcss": "^8.4.30", "prettier": "3.0.3", "tailwindcss": "^3.3.3" @@ -2025,7 +2026,6 @@ "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "dev": true, "hasInstallScript": true, "optional": true, "os": [ @@ -3161,6 +3161,17 @@ } } }, + "node_modules/next-themes": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/next-themes/-/next-themes-0.2.1.tgz", + "integrity": "sha512-B+AKNfYNIzh0vqQQKqQItTS8evEouKD7H5Hj3kmuPERwddR2TxvDSFZuTj6T7Jfn1oyeUyJMydPl1Bkxkh0W7A==", + "dev": true, + "peerDependencies": { + "next": "*", + "react": "*", + "react-dom": "*" + } + }, "node_modules/next/node_modules/postcss": { "version": "8.4.14", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.14.tgz", diff --git a/package.json b/package.json index 09efabb..f2e38e9 100644 --- a/package.json +++ b/package.json @@ -25,6 +25,7 @@ "autoprefixer": "^10.4.15", "husky": "^8.0.3", "lint-staged": "^14.0.1", + "next-themes": "^0.2.1", "postcss": "^8.4.30", "prettier": "3.0.3", "tailwindcss": "^3.3.3" diff --git a/src/app/layout.jsx b/src/app/layout.jsx index 9faa593..ccef5aa 100644 --- a/src/app/layout.jsx +++ b/src/app/layout.jsx @@ -1,12 +1,15 @@ 'use client' +import { ThemeProvider } from 'next-themes' import './global.css' export default function RootLayout({ children }) { return ( - + -
{children}
+ +
{children}
+
) diff --git a/src/app/page.jsx b/src/app/page.jsx index 616f32d..7efded3 100644 --- a/src/app/page.jsx +++ b/src/app/page.jsx @@ -1,5 +1,7 @@ 'use client' +import { useState, useEffect } from 'react' +import { useTheme } from 'next-themes' import Message from '@/components/message' const now = Date.now() @@ -14,6 +16,21 @@ const MOCK_MESSAGES = [ ] export default function Home() { + const [mounted, setMounted] = useState(false) + const { resolvedTheme, setTheme } = useTheme() + + useEffect(() => { + setMounted(true) + }, []) + + if (!mounted) { + return null + } + + const toggleThemeHandler = () => { + setTheme(resolvedTheme === 'dark' ? 'light' : 'dark') + } + return (
{MOCK_MESSAGES.map(({ sentAt, content }, i) => ( @@ -21,6 +38,12 @@ export default function Home() { {content} ))} +
) }