Skip to content

Instantly share code, notes, and snippets.

@bartimaeus
Created August 16, 2018 03:19
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 bartimaeus/4391baf05a1c495d168cdf4ac091b58c to your computer and use it in GitHub Desktop.
Save bartimaeus/4391baf05a1c495d168cdf4ac091b58c to your computer and use it in GitHub Desktop.
Lesson 04
/*
Create a `withStorage` higher order component that manages saving and retrieving
the `sidebarIsOpen` state to local storage
*/
import "./index.css";
import React from "react";
import MenuIcon from "react-icons/lib/md/menu";
import { set, get, subscribe } from "./local-storage";
const withStorage = (storageKey, defaultValue) => Comp => {
return class WithStorage extends React.Component {
state = {
storageValue: get(storageKey, defaultValue)
};
componentDidMount() {
this.unsubscribe = subscribe(() => {
this.setState({
storageValue: get(storageKey)
});
});
}
setStorage = value => {
set(storageKey, value);
};
componentWillUnmount() {
this.unsubscribe();
}
render() {
return <Comp {...this.state} setStorage={this.setStorage} />;
}
};
};
class App extends React.Component {
render() {
const { storageValue: sidebarIsOpen, setStorage } = this.props;
return (
<div className="app">
<header>
<button
className="sidebar-toggle"
title="Toggle menu"
onClick={() => setStorage(!sidebarIsOpen)}
>
<MenuIcon />
</button>
</header>
<div className="container">
<aside className={sidebarIsOpen ? "open" : "closed"} />
<main />
</div>
</div>
);
}
}
export default withStorage("sidebarIsOpen", false)(App);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment