Skip to content

Instantly share code, notes, and snippets.

@jlongster jlongster/ElementQuery.js
Last active Jan 10, 2018

Embed
What would you like to do?
<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);
}
});
@manojkumarm

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.