Skip to content

Instantly share code, notes, and snippets.

@charliewilco
Created October 12, 2018 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charliewilco/aa2528ba0d47a79739a0c046ae0b735c to your computer and use it in GitHub Desktop.
Save charliewilco/aa2528ba0d47a79739a0c046ae0b735c to your computer and use it in GitHub Desktop.
Night Mode + Localstorage
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