Why do MediaQueryLists make me feel so dirty?

I've been looking at how to implement media queries in my js, and while they work, they just leave me feeling... ugh. I know window.matchMedia() returns a MediaQueryList (mql), an object which has a property matches, and has an onChange listener. So in an arbitrary view I'll call the following to get all the mql objects for my breakpoints this._mqls = getMediaQueryLists(this._setLeft)
export const getMediaQueryLists = (cb) => {
const screens = {
small : null,
medium: window.matchMedia( '(min-width: 400px)' ),
large : window.matchMedia( '(min-width: 800px)' ),
// etc...
};

for(let[scr, mql] of Object.entries(screens)) {
if(mql) mql.addEventListener('change', cb)
}

return screens;
}
export const getMediaQueryLists = (cb) => {
const screens = {
small : null,
medium: window.matchMedia( '(min-width: 400px)' ),
large : window.matchMedia( '(min-width: 800px)' ),
// etc...
};

for(let[scr, mql] of Object.entries(screens)) {
if(mql) mql.addEventListener('change', cb)
}

return screens;
}
and then in the callback I'll check for the screen sizes
setLeft() {

let size = null;
for (let [scr, mql] of Object.entries(this._mqls)) {
if (!mql || mql.matches) size = scr;
}

// Do things based on screen size
console.log(size);
}
setLeft() {

let size = null;
for (let [scr, mql] of Object.entries(this._mqls)) {
if (!mql || mql.matches) size = scr;
}

// Do things based on screen size
console.log(size);
}
Is this really the right way to do it? I guess I can use another helper to get the size (which would make it feel a little cleaner), but still 🤢
2 Replies
MarkBoots
MarkBoots•2y ago
maybe you can try to bind the matched screen entry to the callbackfunction
for(let[scr, mql] of Object.entries(screens)) {
cb.bind({src:mql})
if(mql) mql.addEventListener('change', cb)
}
for(let[scr, mql] of Object.entries(screens)) {
cb.bind({src:mql})
if(mql) mql.addEventListener('change', cb)
}
in the callback it will be accessible by this.scr and you wont have to loop over it *(I didn't test it, but theoretically, it should work) *
JWode
JWode•2y ago
hmm, interesting, I'll give that a go, thanks!
Want results from more Discord servers?
Add your server