Created
August 16, 2018 03:19
-
-
Save bartimaeus/4391baf05a1c495d168cdf4ac091b58c to your computer and use it in GitHub Desktop.
Lesson 04
This file contains hidden or 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
/* | |
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