Skip to content

Instantly share code, notes, and snippets.

@steveruizok
Created August 29, 2018 14:01
Show Gist options
  • Select an option

  • Save steveruizok/7729da66dff10add42b42aa41ff0f8f4 to your computer and use it in GitHub Desktop.

Select an option

Save steveruizok/7729da66dff10add42b42aa41ff0f8f4 to your computer and use it in GitHub Desktop.
import React from "react";
const debounce = (func, delay) => {
let inDebounce;
return function() {
const context = this;
const args = arguments;
clearTimeout(inDebounce);
inDebounce = setTimeout(() => func.apply(context, args), delay);
};
};
export class Responsive extends React.Component {
elem = React.createRef();
width;
state = {
size: "initial",
content: null
};
resize = debounce(this.compose, 150);
componentDidMount() {
this.compose();
window.addEventListener("resize", this.resize);
}
componentWillUnmount() {
window.removeEventListener("resize", this.resize);
}
compose = () => {
let size, content;
const width = this.elem.current.clientWidth;
if (width < 340) {
size = "xs";
} else if (width < 400) {
size = "s";
} else if (width < 460) {
size = "m";
} else {
size = "l";
}
if (this.state.size === size) {
return;
}
switch (size) {
case "s":
content = <div>small</div>;
break;
case "m":
content = <div>medium</div>;
break;
case "l":
content = <div>large.</div>;
break;
}
this.setState({
size: size,
content: content
});
};
render() {
return <div ref={this.elem}>{this.state.content}</div>;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment