Skip to content

Instantly share code, notes, and snippets.

@inPhoenix
Last active January 23, 2019 15:32
Show Gist options
  • Save inPhoenix/b692249122b284aaee8bee118e4eca38 to your computer and use it in GitHub Desktop.
Save inPhoenix/b692249122b284aaee8bee118e4eca38 to your computer and use it in GitHub Desktop.
Get the Window Size for React Render using (Render callback / function as a Child / render props / props.children as a function) pattern
// https://medium.com/@martin_hotell/react-children-composition-patterns-with-typescript-56dfc8923c64
// https://www.robinwieruch.de/react-render-props-pattern/
// https://www.youtube.com/watch?v=AiJ8tRRH0f8
// https://www.youtube.com/watch?v=BcVAq3YFiuc
constructor () {
this.state = {
width: 0,
...
}
}
componentDidMount() {
this.setState( { width: window.innerWidth },
window.addEventListener("resize", ({ target }) => this.setState({ width: target.innerWidth }))
)
}
render() {
const FunctionAsAChild = ({ children }) => children(this.state.width)
...
return (
<div>
<FunctionAsAChild>
{(width) => <div className='Box'> width is {width} </div>}
</FunctionAsAChild>
</div>
)
--------------------------------------------------------------------------------------------------------------
Example enhanced:
const FunctionAsAChild = ({ children }) => {
const become = this.state.width + 100
console.log('%c become', 'background: midnightblue; color: deepskyblue', become);
return (children(become))
}
render() {
return (
<FunctionAsAChild>
{(width) => {
return (
<div>
{width >= 600 ? (<div>large</div>) : (<div> too small</div>)}
<div className='Box'> width is {width} </div>
</div>
)
}}
</FunctionAsAChild>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment