Skip to content

Instantly share code, notes, and snippets.

@jlongster
Last active March 19, 2021 23:42
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jlongster/53dc885f1e991e1b454bb25a0496f646 to your computer and use it in GitHub Desktop.
Save jlongster/53dc885f1e991e1b454bb25a0496f646 to your computer and use it in GitHub Desktop.
<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>;
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);
}
});
@rainforest-of-code
Copy link

rainforest-of-code commented Dec 4, 2017

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment