Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.