Created
June 25, 2020 12:40
-
-
Save velotiotech/a1dff9ce781015f2a7e274529080f8ed to your computer and use it in GitHub Desktop.
Cleaner Efficient Code with Hooks and Functional Programming - Wrapper Hell issue - Media component using render props
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
import React from "react"; | |
export default class Media extends React.Component { | |
removeListener = () => null; | |
constructor(props) { | |
super(props); | |
this.state = { | |
matches: window.matchMedia(this.props.query).matches | |
}; | |
} | |
componentDidMount() { | |
this.init(); | |
} | |
init() { | |
const media = window.matchMedia(this.props.query); | |
if (media.matches !== this.state.matches) { | |
this.setState({ matches: media.matches }); | |
} | |
const listener = () => this.setState({ matches: media.matches }); | |
media.addListener(listener); | |
this.removeListener = () => media.removeListener(listener); | |
} | |
componentDidUpdate(prevProps) { | |
if (prevProps.query !== this.props.query) { | |
this.removeListener(); | |
this.init(); | |
} | |
} | |
componentWillUnmount() { | |
this.removeListener(); | |
} | |
render() { | |
return this.props.children(this.state.matches); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment