Created
November 19, 2017 20:47
-
-
Save MartinL83/715548a0c7c90e91112ca75baf38f6b3 to your computer and use it in GitHub Desktop.
A simple React HOC to feed css breakpoint data to a component.
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 _ from 'lodash'; | |
/* | |
HOC to feed breakpoints data to child component. | |
Breakpoint data is based on Bootstrap's breakpoints | |
Using lodash throttle to optimize the high rate of events being fired. | |
*/ | |
export const Breakpoints = (WrappedComponent) => { | |
return class BreakpointComponent extends Component { | |
state = { | |
currentBreakpoint : undefined, | |
activeBreakpoints : undefined, | |
breakpoints : [ | |
{name: 'xs', value: 0}, | |
{name: 'sm', value: 576}, | |
{name: 'md', value: 768}, | |
{name: 'lg', value: 992}, | |
{name: 'xl', value: 1200} | |
] | |
} | |
componentDidMount(){ | |
window.addEventListener('resize', this.handleResize, false); | |
this.calculateBreakpoint(); | |
} | |
componentWillUnmount(){ | |
this.handleResize.cancel; | |
window.removeEventListener('resize', this.handleResize, false); | |
} | |
handleResize = _.throttle(() => { | |
this.calculateBreakpoint(); | |
}, 500 ); | |
calculateBreakpoint = () => { | |
const current = this.state.breakpoints.filter( x => x.value >= window.innerWidth )[0]; | |
const active = this.state.breakpoints.filter( x => x.value <= window.innerWidth ); | |
this.setState({ | |
currentBreakpoint : current, | |
activeBreakpoints : active | |
}); | |
} | |
render(){ | |
return ( | |
<WrappedComponent {...this.props} {...this.state} /> | |
) | |
} | |
} | |
} |
React hook version:
export const withBreakpoint = (Component) => {
return (props) => {
const [state, setState] = useState({
currentBreakpoint: undefined,
activeBreakpoints: undefined,
breakpoints: [
{ name: 'xs', value: 0 },
{ name: 'sm', value: 576 },
{ name: 'md', value: 768 },
{ name: 'lg', value: 992 },
{ name: 'xl', value: 1200 }
]
});
useEffect(() => {
window.addEventListener('resize', handleResize, false);
calculateBreakpoint();
return () => {
handleResize.cancel;
window.removeEventListener('resize', handleResize, false);
};
}, []);
const handleResize = _.throttle(() => {
calculateBreakpoint();
}, 500);
const calculateBreakpoint = () => {
const current = state.breakpoints.filter(x => x.value >= window.innerWidth)[0];
const active = state.breakpoints.filter(x => x.value <= window.innerWidth);
setState({
currentBreakpoint: current,
activeBreakpoints: active
});
}
return (
<Component {...props} {...state} />
)
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to use it please?