Created
October 12, 2018 08:20
-
-
Save charliewilco/aa2528ba0d47a79739a0c046ae0b735c to your computer and use it in GitHub Desktop.
Night Mode + Localstorage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
const Night = React.createContext({}); | |
export class NightModeProvider extends React.Component { | |
static defaultProps = { | |
className: "NightMode" | |
}; | |
state = { | |
night: false | |
}; | |
updateNightMode = () => this.setState(({ night }) => ({ night: !night })); | |
setNightMode = status => { | |
const { className } = this.props; | |
const html = document.querySelector("html"); | |
if (html) { | |
localStorage.setItem("nightMode", status.toString()); | |
if (status) { | |
html.classList.add(className); | |
} else { | |
html.classList.remove(className); | |
} | |
} | |
}; | |
componentDidMount() { | |
let night = JSON.parse(localStorage.getItem("nightMode")) || false; | |
this.setState({ night }); | |
} | |
componentDidUpdate(prevProps, prevState) { | |
const { night } = this.state; | |
if (prevState.night !== night) { | |
this.setNightMode(night); | |
} | |
} | |
render() { | |
const { night } = this.state; | |
return ( | |
<Night.Provider value={{ night, actions: { onToggleNightMode: this.updateNightMode } }}> | |
{this.props.children} | |
</Night.Provider> | |
); | |
} | |
} | |
export const withNightMode = Component => { | |
return class extends React.Component { | |
static displayName = `withNightMode(${Component.displayName || Component.name})`; | |
render() { | |
return <Night.Consumer>{context => <Component {...context} />}</Night.Consumer>; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment