Last active
July 11, 2018 13:09
-
-
Save victorfern91/98c652f985b930cbd6c353a1a62e1533 to your computer and use it in GitHub Desktop.
React responsive components
This file contains 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
function withResizeObserver(Component, responsiveLimits = { sm: 540, md: 720, lg: 960, xl: 1200 }) { | |
return class extends React.Component { | |
constructor() { | |
super(); | |
this.state = { | |
width: 0, | |
componentDimension: "sm" | |
}; | |
} | |
/** | |
* During the component initialization we need to initialize the `ResizeObserver` for this expecific | |
* components. | |
*/ | |
componentDidMount() { | |
this.resizeObserver = new window.ResizeObserver(entries => this._onComponentResize(entries[0])); | |
this.resizeObserver.observe(ReactDOM.findDOMNode(this)); | |
} | |
/** | |
* Remove the `ResizeObserver` when the component it's unmounted from the DOM. | |
*/ | |
componentWillUnmount() { | |
this.resizeObserver.unobserve(ReactDOM.findDOMNode(this)); | |
} | |
/** | |
* When the component has an update in his horizontal dimensions we should run this function | |
* and get the current dimension classname. | |
*/ | |
_onComponentResize(entry) { | |
const componentWidth = entry.target.clientWidth; | |
let componentDimension = "sm"; | |
if (componentWidth > responsiveLimits.sm && componentWidth <= responsiveLimits.md) { | |
componentDimension = "md"; | |
} else if (componentWidth > responsiveLimits.md && componentWidth <= responsiveLimits.lg) { | |
componentDimension = "lg"; | |
} else if (componentWidth > responsiveLimits.lg) { | |
componentDimension = "xl"; | |
} | |
this.setState({ | |
width: componentWidth, | |
componentDimension | |
}); | |
} | |
render() { | |
const props = { | |
...this.props, | |
className: `${this.props.className} ${this.state.componentDimension}` | |
}; | |
return ( | |
<Component width={this.state.width} componentDimension={this.state.componentDimension} {...props} /> | |
); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment