🐷

【Next.js】Next.js & Contentful BlogApp 【18Colormode Context】

2022/12/04に公開

【18Colormode Context】

YouTube:https://youtu.be/cIZHfVdQBpU

https://youtu.be/cIZHfVdQBpU

今回はContextを作成して、ダークモードとライトモードを
切り替えられるようにします。

context/colormodeContext.js
import { createContext, useContext, useState } from 'react'

const ColormodeContext = createContext({})

export const ColormodeContextProvider = ({ children }) => {
  const [color, setColor] = useState('dark')

  return (
    <ColormodeContext.Provider value={{ color, setColor }}>
      {children}
    </ColormodeContext.Provider>
  )
}

export const useColormodeContext = () => useContext(ColormodeContext)
pages/_app.js
import { ColormodeContextProvider } from '../context/colormodeContext'
import '../styles/globals.css'

function MyApp({ Component, pageProps }) {
  return (
    <ColormodeContextProvider>
      <Component {...pageProps} />
    </ColormodeContextProvider>
  )
}

export default MyApp
components/Layout.js
import Head from 'next/head'
import { useColormodeContext } from '../context/colormodeContext'
import Navbar from './Navbar'

const Layout = ({ children, title = 'My Blog App' }) => {
  const { color } = useColormodeContext()

  return (
    <div className={`${color}`}>
      <Head>
        <title>{title}</title>
      </Head>

      <div className="w-full min-h-screen bg-gradient-to-r from-yellow-500 to-red-500 dark:from-purple-800 dark:to-pink-600">
        <Navbar />
        <main>{children}</main>

        <footer className="py-3 text-center dark:text-white">
          <span>&copy; My Blog App</span>
        </footer>
      </div>
    </div>
  )
}

export default Layout

Discussion