Skip to content

Instantly share code, notes, and snippets.

@bekhzod91
Forked from gaearon/MyResponsiveComponent.js
Last active November 4, 2018 13:35
Show Gist options
  • Save bekhzod91/69c4a241f851f282798a441dcec509d1 to your computer and use it in GitHub Desktop.
Save bekhzod91/69c4a241f851f282798a441dcec509d1 to your computer and use it in GitHub Desktop.
Examples from "Making Sense of React Hooks"
import React from "react";
import ReactDOM from "react-dom";
import { useWindowWidth } from "./wrapper";
function MyResponsiveComponent({ width }) {
return <div className="App">Window width: {width}</div>;
}
const App = useWindowWidth(WindowResize);
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
import React from "react";
export function useWindowWidth(Wrapper) {
return class Media extends React.PureComponent {
constructor(props) {
super(props);
this.state = { width: window.innerWidth };
}
componentDidMount() {
window.addEventListener("resize", this.handleResize);
}
componentWillUnmount() {
window.removeEventListener("resize", this.handleResize);
}
handleResize = () => {
this.setState({ width: window.innerWidth });
};
render() {
return <Wrapper width={this.state.width} />;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment