This bit of code gets a queryList and Component passed to it.
Use it like: const MediaMatchingComponent = mediaQueryHoc(queryList, MyComponent);
A queryList is the return of something like window.matchMedia('(max-width: 50rem)');
const React = require('react'); | |
const mediaQueryHoc = function(queryList, Component) { | |
class AddMediaQuery extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
mediaQueryMatches: false, | |
}; | |
this.handleScreenChange = this.handleScreenChange.bind(this); | |
} | |
handleScreenChange() { | |
if(queryList.matches !== this.state.isSmallScreen) { | |
this.setState({ | |
mediaQueryMatches: queryList.matches, | |
}); | |
} | |
} | |
componentWillMount() { | |
if(queryList.matches) { | |
this.setState({ | |
mediaQueryMatches: true, | |
}); | |
} | |
queryList.addListener(this.handleScreenChange); | |
} | |
componentWillUnmount() { | |
queryList.removeListener(this.handleScreenChange); | |
} | |
render() { | |
return( | |
<Component {...this.props} mediaQueryMatches={this.state.mediaQueryMatches} /> | |
); | |
} | |
} | |
return AddMediaQuery; | |
}; | |
module.exports = mediaQueryHoc; |