Created
December 23, 2016 02:15
-
-
Save SvitlanaShepitsena/874259cbc226edbbd61d19acd9a04587 to your computer and use it in GitHub Desktop.
width customized
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
import React, {Component} from "react"; | |
import EventListener from "react-event-listener"; | |
export const X_SMALL = 1; | |
export const SMALL = 2; | |
export const H_SMALL = 3; | |
export const MEDIUM = 4; | |
export const X_MEDIUM = 5; | |
export const LARGE = 6; | |
export default function withWidth2(options = {}) { | |
const { | |
resizeInterval = 100, | |
} = options; | |
return (MyComponent) => { | |
return class WithWidth2 extends Component { | |
constructor(props) { | |
super(props) | |
this.state = { | |
width: this.getWidth(), | |
}; | |
} | |
componentDidMount() { | |
this.updateWidth(); | |
} | |
componentWillUnmount() { | |
clearTimeout(this.deferTimer); | |
} | |
handleResize = () => { | |
clearTimeout(this.deferTimer); | |
this.deferTimer = setTimeout(() => { | |
this.updateWidth(); | |
}, resizeInterval); | |
}; | |
getWidth() { | |
const innerWidth = window.innerWidth; | |
let width; | |
if (innerWidth >= 1100) { | |
width = LARGE; | |
} | |
else if (innerWidth >= 992) { | |
width = X_MEDIUM; | |
} | |
else if (innerWidth >= 736) { | |
width = MEDIUM; | |
} | |
else if (innerWidth >= 568) { | |
width = H_SMALL; | |
} | |
else if (innerWidth >= 330) { | |
width = SMALL; | |
} | |
else { // innerWidth < 768 | |
width = X_SMALL; | |
} | |
return width; | |
} | |
updateWidth() { | |
let width = this.getWidth(); | |
if (width !== this.state.width) { | |
this.setState({ | |
width: width, | |
}); | |
} | |
} | |
render() { | |
return ( | |
<EventListener target="window" onResize={this.handleResize}> | |
<MyComponent | |
{...this.props} | |
width={this.state.width} | |
/> | |
</EventListener> | |
); | |
} | |
}; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment