From 43cadc9bd4be80570452a6baddfccdb278448064 Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Sun, 24 Jun 2018 18:20:34 +0200 Subject: [PATCH] persist theme switch state * set initial state based on local storage * set local storage when switch is clicked * continue switrching between day/night, but only if no local storage key is found --- src/components/molecules/ThemeSwitch.jsx | 63 ++++++++++++------------ src/components/organisms/Header.jsx | 48 ++++++++++-------- 2 files changed, 60 insertions(+), 51 deletions(-) diff --git a/src/components/molecules/ThemeSwitch.jsx b/src/components/molecules/ThemeSwitch.jsx index 438ce2d..92d9e12 100644 --- a/src/components/molecules/ThemeSwitch.jsx +++ b/src/components/molecules/ThemeSwitch.jsx @@ -1,34 +1,36 @@ import React, { PureComponent, Fragment } from 'react' import PropTypes from 'prop-types' import Helmet from 'react-helmet' -import { FadeIn } from '../atoms/Animations' import Day from '../svg/Day' import Night from '../svg/Night' import styles from './ThemeSwitch.module.scss' -const ThemeToggle = props => { - return ( - - - - - - ) -} +const ThemeToggle = props => ( + + + + + +) class ThemeSwitch extends PureComponent { constructor(props) { super(props) - this.state = { dark: false } + if (localStorage.getItem('dark') === 'true') { + this.state = { dark: true } + } else if (localStorage.getItem('dark') === 'false') { + this.state = { dark: null } + } else { + this.state = { dark: null } + } } componentDidMount() { const now = new Date().getHours() + const darkLocalStorage = localStorage.getItem('dark') + + if (darkLocalStorage) return if (now >= 19 || now <= 7) { this.setState({ dark: true }) @@ -39,6 +41,7 @@ class ThemeSwitch extends PureComponent { handleChange = () => { this.setState({ dark: !this.isDark() }) + localStorage.setItem('dark', !this.isDark()) } render() { @@ -47,22 +50,20 @@ class ThemeSwitch extends PureComponent { - - - + ) } diff --git a/src/components/organisms/Header.jsx b/src/components/organisms/Header.jsx index 8f3ce7b..fce2edc 100644 --- a/src/components/organisms/Header.jsx +++ b/src/components/organisms/Header.jsx @@ -1,35 +1,43 @@ -import React from 'react' +import React, { PureComponent } from 'react' import { Link } from 'gatsby' import PropTypes from 'prop-types' -import { FadeIn } from '../atoms/Animations' import Networks from '../molecules/Networks' import Availability from '../molecules/Availability' import ThemeSwitch from '../molecules/ThemeSwitch' import LogoUnit from '../atoms/LogoUnit' import styles from './Header.module.scss' -const Header = ({ meta, isHomepage }) => ( -
- - - - - - +class Header extends PureComponent { + constructor(props) { + super(props) + } - + render() { + const { isHomepage, meta } = this.props - -
-) + return ( +
+ + + + + + + + + +
+ ) + } +} Header.propTypes = { - meta: PropTypes.object, - isHomepage: PropTypes.bool + isHomepage: PropTypes.bool, + meta: PropTypes.object } export default Header