Skip to content
Permalink
Browse files

Use hooks for theme

  • Loading branch information...
wgao19 committed May 22, 2019
1 parent c2a4dad commit df8f57d9ab9fbb4c9f6837dc6d43833d6b63d662
Showing with 35 additions and 41 deletions.
  1. +35 −41 src/components/Layout/index.js
@@ -1,52 +1,46 @@
// @flow

import React from 'react'
import React, { useState, useEffect } from 'react'
import cx from 'classnames'
import Header from '../Header'
import Footer from '../Footer'
import s from './s.module.scss'
import './prism-reset.css'

class Layout extends React.Component {
constructor(props) {
super(props)
this.state = {
toggle:
typeof window !== 'undefined'
? window.localStorage.getItem('theme') === 'true'
? true
: false
: false,
}
}
render() {
const { children, location } = this.props
return (
<>
<base target="_blank" />
<main>
<div className={s.bg} />
<div
className={cx(s.toggle, this.state.toggle ? null : s.hasZIndex)}
onClick={() => {
this.setState(() => {
typeof window !== 'undefined'
? window.localStorage.setItem('theme', !this.state.toggle)
: null
return { toggle: !this.state.toggle }
})
}}
/>
<div
className={cx(s.blender, this.state.toggle ? s.expanded : null)}
/>
<Header location={location} />
<div>{children}</div>
<Footer />
</main>
</>
)
const THEMES = ['sun', 'moon']
const getNewTheme = currentTheme => THEMES[1 - THEMES.indexOf(currentTheme)]

const Layout = props => {
const [theme, setTheme] = useState(
typeof window !== 'undefined'
? window.localStorage.getItem('theme')
: THEMES[0]
)
const toggleTheme = currentTheme => {
const newTheme = getNewTheme(currentTheme)
setTheme(newTheme)
}
useEffect(() => {
typeof window !== 'undefined' && window.localStorage.setItem('theme', theme)
}, [theme])
const { children, location } = props
return (
<>
<base target="_blank" />
<main>
<div className={s.bg} />
<div
className={cx(s.toggle, theme === THEMES[1] ? null : s.hasZIndex)}
onClick={toggleTheme.bind(null, theme)}
/>
<div
className={cx(s.blender, theme === THEMES[1] ? s.expanded : null)}
/>
<Header location={location} />
<div>{children}</div>
<Footer />
</main>
</>
)
}

export default Layout

0 comments on commit df8f57d

Please sign in to comment.
You can’t perform that action at this time.