Giter Site home page Giter Site logo

react-media-query-hoc's Introduction

react-media-query-hoc Build Status NPM Version Badge

A dead simple React Higher Order Component (HOC) that uses context for matching media queries.

Why use this?

  • A simple API which doesnt require you to put MediaQuery components all over your code base
  • More performant (you only need 1 parent MediaQueryProvider that listens to media events you wish to configure)
  • Easier to test than other react media query libraries
  • Small bundlephobia
  • Uses css-mediaquery which parses and determines if a given CSS Media Query matches a set of values (used for server side rendering).
  • You want specific react components being mounted and rendered based on media types

Why not use this?

We generally recommend using vanilla CSS media queries to build responsive websites, this is simpler, provides a smoother UX, also it mitigates having to guess the screen width during server side rendering. Use this library if you need to dramatically alter the page layout between media types (some examples include: an experiment needs to be run on a specific screen width or an advertisement needs to be on specific screen width).

Install

Via NPM:

npm install react-media-query-hoc --save

Via Yarn:

yarn add react-media-query-hoc

Usage

This library is designed so that you have 1 MediaQueryProvider parent and 1-many child components wrapped with withMedia HOC

MediaQueryProvider

This component will listen to media events you want to configure, it should be used once as a parent component.

Usage:

import { MediaQueryProvider } from 'react-media-query-hoc';

const App = (props) => {
  return (
    <MediaQueryProvider>
      <TheRestOfMyApp />
    </MediaQueryProvider>
  );
};

export default App;

By providing no queries prop to the MediaQueryProvider component, it will default to these media queries

But you can provide different media queries for your use case using the queries prop, eg:

const App = (props) => {
  const customQueries = {
    verySmall: 'screen and (max-width: 300px)',
    someOtherMediaQuery: 'screen and (min-width: 301px)',
  };

  return (
    <MediaQueryProvider queries={customQueries}>
      <TheRestOfMyApp />
    </MediaQueryProvider>
  );
};

withMedia

This is a HOC to provide media match props to your component.

Usage:

import { withMedia } from 'react-media-query-hoc';

const MyComponent = ({ media, ...props}) => {
  if (media.tablet || media.mobile) {
    return (
      <div>
        Mobile and Tablet View
      </div>
    )
  }

  return (
    <div>
      Other View
    </div>
  );
};

export const BaseMyComponent = MyComponent;
export default withMedia(MyComponent);

Components wrapped by withMedia() won't work with React's usual ref mechanism, because the ref supplied will be for withMedia rather than the wrapped component. Therefore a prop, wrappedRef provides the same function. Note: this means the wrapped component can not be a stateless function.

MediaContext

This is the React Context exported and ready to be used with React useContext hook. It has a default value of {}, present when the component that consumes the context is not wrapped with MediaQueryProvider.

import { MediaContext } from 'react-media-query-hoc';
import { useContext } from 'react';

const MyComponent = (props) => {
  const media = useContext(MediaContext);

  if(media.tablet || media.mobile) {
    return (
      <div>
        Mobile and Tablet View
      </div>
    )
  }

  return (
    <div>
      Other View
    </div>
  );
};

export default MyComponent;

// default value
ReactDOM.render(<MyComponent />);     // Renders 'Other View';

Server Side Rendering

You can pass in media features from your server, all supported values can be found here.

Usage (matches mobile screen during SSR):

const App = (props) => {
  const values = {
    width: 300,
    type: 'screen',
  };

  return (
    <MediaQueryProvider values={values}>
      <TheRestOfMyApp />
    </MediaQueryProvider>
  );
};

React 16 ReactDOM.hydrate

It's very important to realise a server client mismatch is dangerous when using hydrate in React 16, ReactDOM.hydrate can cause very strange html on the client if there is a mismatch. To mitigate this we use the two-pass rendering technique mentioned in the React docs. We render on the client in the first pass using values with css-mediaquery used on the server, then we use the browsers native window.matchMedia to get it's actual dimensions and render again if it causes different query results. This means there should be no React server/client mismatch warning in your console and you can safely use hydrate. As a result of above, if you are server side rendering and using ReactDOM.hydrate you must supply MediaQueryProvider a values prop.

Browser Support

The oldest browser we support is IE11, if you want to support even older browsers please make sure you are using a polyfill for Map such as babel-polyfill.

Testing Components

Because the media queries and context are abstracted out you can easily test components with or without the withMedia HOC, just ensure you export your component base without the HOC as well, eg:

export const BaseMyComponent = MyComponent;
export default withMedia(MyComponent);

Then in your React tests you can import like:

import { BaseMyComponent } from 'location_of_my_component';

And unit test the component without having to worry about context

Thanks

Big thanks to the maintainers of these repos

Both libraries are a bit similar, but my original use case required the extra advantages listed in Why use this?

react-media-query-hoc's People

Contributors

ah-simonkrix avatar albertstill avatar gabrielmeridadomain avatar gricard avatar jooj123 avatar mohamedmagdy17593 avatar mostafaelganainy avatar tomdaniels avatar xanido avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

react-media-query-hoc's Issues

Prevent MediaQueryProvider from printing any additional div

As the MediaQueryProvider component should be used at the root-level of the application as stated in the docs, it makes no sense that it adds an additional element to the HTML structure. In my case, using a layout based on flexboxes that div that gets printed is a problem. Maybe you could use Children.only like Apollo Client does to make this component "transparent"?

withMedia hoc can cause jumpy behaviour

Should withMedia render the component before context.media is defined?
We've seen cases where we can see a jump where it renders the default view, and then when the media prop is defined it jumps to say the mobile view.
I believe react-responsive won't render its children before media is defined.

Changelog for v1.0 ?

Hello,

Is it possible to have a changelog or at least the breaking changes from v0.5 to v1.0 ?

Thanks !

Allow passing of values to matchmedia for Server Side Rendering

Server rendering can be done if there is way to pass static values such as deviceWidth, deviceHeight etc so that on client mount there is no client / server mismatch issues (matchmedia lib can handle this)

Interface could be:

const App = (props) => {
  const customQueries = {
    verySmall: 'screen and (max-width: 300px)',
    someOtherMediaQuery: 'screen and (min-width: 301px)',
  }; 

  const values = {
    deviceWidth: 500,
    orientation: 'portrait',
  };

  return (
    <MediaQueryProvider queries={customQueries} values={values}>
      <TheRestOfMyApp />
    </MediaQueryProvider>
  );
};

Fix Travis badge

The travis CI badge links to a build which says
"No builds for this repository" but there was builds at some point?

I think the config has gone haywire - requires some small investigation to resolve

Context is not updated when state changes

I'm using React 16 with a component wrapped inside the withMedia HOC. Media queries works fine, refreshing the whole page at different resolutions I see that the state/context of the MediaQueryProvider component is correctly updated. However, resizing the window updates the state but not the context, so any child component won't see the new media queries values and won't trigger any layout change.

State being updated on window resize, context isn't.

Hello,

I have a Component that is wrapped by the withMedia HOC.

When I resize the window, I can see that the MediaQueryProvider's state is currently updating to the correct media device, but the context of the withMedia HOC is not.

In order for the wrapped components and withMediaHOC to reflect the right device in context/props, I have to refresh the page.

I'm currently using React 16.

Here is how I'm using the MediaQueryProvider

screen shot 2018-05-25 at 9 50 32 am

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.