r/javascript • • Aug 21 '18

Effectively supported in all browsers, JavaScript has its own form of media queries just like CSS.

https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia
465 Upvotes

114 comments sorted by

View all comments

26

u/elysgaard Aug 22 '18

Been using this in our React/Redux app for a while now and it's awesome being able to programatically change how components are rendered based on screen sizes.

const MyComponent = ({isMobile}) => {
    if (isMobile) {
        return <div>You're on mobile size!</div>
    }
    return <div>Do the normal stuff</div>
};
export default compose(
    responsiveState(['isMobile'])
)(MyComponent);    

We listen to the changes with

import {Observable} from 'rxjs';
const mediaQueries = window.matchMedia('...');
const mediaQueryEvent = Observable.create((observer) => {
    mediaQueries.addListener(e => observer.next(e));
}).share();

Then the responsiveState high-order-component has something similar to this

componentDidMount() {
    this.mediaSubscription = mediaQueryEvent.subscribe(...);
}

This means than we only have one listener to the media queries no matter how many components are using it at the same time.

1

u/Console-DOT-N00b Aug 28 '18

Or better yet...just slightly change things.... to make people think they are insane...