Last active
March 19, 2021 23:42
-
-
Save jlongster/53dc885f1e991e1b454bb25a0496f646 to your computer and use it in GitHub Desktop.
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
<ElementQuery sizes={[{ width: 350, size: 'small' }, { size: 'big' }]}> | |
{(matched, ref) => ( | |
<div ref={ref}> | |
{/* `matched` is the object that got matched, it's the literal | |
object from your array above so you can put anything into it. | |
The last item will be matched by default if nothing else does. | |
Also, `matched` will be null on initial render since it doesn't | |
have the size and it's up to you to render what you want in that | |
case.*/} | |
{matched | |
? matched.size === 'big' ? 'This is big' : 'This is small' | |
: "I don't know yet"} | |
</div> | |
)} | |
</ElementQuery>; |
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'; | |
import lively from 'lively'; | |
// Global registry and resize handler | |
let _registeredInstances = []; | |
function register(inst) { | |
if (_registeredInstances.length === 0) { | |
window.addEventListener('resize', onResize); | |
} | |
_registeredInstances.push(inst); | |
} | |
function unregister(inst) { | |
_registeredInstances = _registeredInstances.filter(i => i !== inst); | |
if (_registeredInstances.length === 0) { | |
window.removeEventListener('resize', onResize); | |
} | |
} | |
function onResize() { | |
_registeredInstances.forEach(inst => { | |
inst.setState({ | |
matched: findMatch(inst.element, inst.props.sizes) | |
}); | |
}); | |
} | |
function findMatch(element, sizes) { | |
const rect = element.getBoundingClientRect(); | |
const matched = sizes.find(size => { | |
return ( | |
(size.width != undefined && rect.width < size.width) || | |
(size.height != undefined && rect.height < size.height) | |
); | |
}); | |
return matched || sizes[sizes.length - 1]; | |
} | |
// Component | |
function ElementQuery({ props: { children }, state: { matched }, inst }) { | |
return children(matched, el => (inst.element = el)); | |
} | |
export default lively(ElementQuery, { | |
getInitialState() { | |
return { matched: null }; | |
}, | |
componentDidMount({ inst }) { | |
register(inst); | |
return { matched: findMatch(inst.element, inst.props.sizes) }; | |
}, | |
componentWillUnmount({ inst }) { | |
unregister(inst); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you very much for this; I also just want to note that https://github.com/d6u/react-container-query has a very similar API