Home

Awesome

React Container Query

True modularity in styling responsive component.

npm version Circle CI Build Status codecov

Build Status

Installation

npm i -D react-container-query

Disclaimer

This code in this repository is provided under an open source license. It's provided by the individuals who contribute to the project in their personal capacity, not by any of their employers.

API

useContainerQuery(query, initialSize?)

Compare the hook style code with the original example from https://github.com/react-container-query/react-container-query#containerquery-queryquery-initialsizewidth-height

Hook Example 1 - Queries against a native DOM element as the container

import React from 'react';
import { useContainerQuery } from 'react-container-query';

const query = {
  'width-between-400-and-599': {
    minWidth: 400,
    maxWidth: 599,
  },
  'width-larger-than-600': {
    minWidth: 600,
  },
};

const MyComponent = () => {
  const [params, containerRef] = useContainerQuery(query);
  return <div ref={containerRef} className={classnames(params)}>the box</div>;
};

Hook Example 2 - Usage for a React component as the container - React.forwardRef

import React from 'react';
import { useContainerQuery } from 'react-container-query';

const query = {
  'width-between-400-and-599': {
    minWidth: 400,
    maxWidth: 599,
  },
  'width-larger-than-600': {
    minWidth: 600,
  },
};

const MyCustomWrapper = React.forwardRef((props, ref) => {
  // MyCustomWrapper really renders a div which wraps the children. 
  // Setting the ref on it allows container query to measure its size.
  return <div ref={ref}>{props.children}</div>
});

const MyComponent = () => {
  const [params, containerRef] = useContainerQuery(query);
  return <MyCustomWrapper ref={containerRef} className={classnames(params)}>the box</div>;
};

<ContainerQuery query={query} initialSize?={{width?, height?}}>

import React, {Component} from 'react';
import {render} from 'react-dom';
import {ContainerQuery} from 'react-container-query';
import classnames from 'classnames';

const query = {
  'width-between-400-and-599': {
    minWidth: 400,
    maxWidth: 599
  },
  'width-larger-than-600': {
    minWidth: 600,
  }
};

function MyComponent() {
  /**
   * `params` in the children function will look like
   * {
   *   'width-between-400-and-599': true,
   *   'width-larger-than-600': false
   * }
   */
  return (
    <ContainerQuery query={query}>
      {(params) => (
        <div className={classnames(params)}>the box</div>
      )}
    </ContainerQuery>
  );
};

/**
 * This will generate following HTML:
 * <div class="width-between-400-and-599"></div>
 */

render(<MyComponent/>, document.getElementById('app'));

properties

applyContainerQuery(Component, query, initialSize?) -> ReactComponent

import React, {Component} from 'react';
import {render} from 'react-dom';
import {applyContainerQuery} from 'react-container-query';
import classnames from 'classnames';

const query = {
  'width-between-400-and-599': {
    minWidth: 400,
    maxWidth: 599
  },
  'width-larger-than-600': {
    minWidth: 600,
  }
};

class Container extends Component {
  render() {
    /**
     * `this.props.containerQuery` will look like
     * {
     *   'width-between-400-and-599': true,
     *   'width-larger-than-600': false
     * }
     */
    return <div className={classnames(this.props.containerQuery)}>the box</div>;
  }
}

const App = applyContainerQuery(Container, query)

/**
 * This will generate following HTML:
 * <div class="width-between-400-and-599"></div>
 */

render(<App/>, document.getElementById('app'));

This is a very similar to <ContainerQuery/>, except it's higher order component style. You don't have to use them together.

Why

Modularity is the heart of component based UI. With most JavaScript modularized, CSS failed to catch up. When developing a responsive web page, we use media queries to toggle styles based on the size of the viewport. This creates problems when creating component level styles. The same component will behave differently when it is placed in different locations on a page. It seriously breaks the modularity of a component. We need components to be responsive and independent of viewport sizes.

What is container query

Container query is a work in process CSS feature. "Container queries allow an author to control styling based on the size of a containing element rather than the size of the user’s viewport." (from Container Query). Container Queries: Once More Unto the Breach is the inspiration of this repo.

With below CSS, .box will be blue when .container is wider than 600px, green when width between 400px and 599px, and red for the rest of time.

.box {
  background-color: red;
}

.container:media(min-width: 400px) {
  .box {
    background-color: green;
  }
}

.container:media(min-width: 600px) {
  .box {
    background-color: blue;
  }
}

Note: This library does not provide these CSS features.

Demo

Checkout CodePen

You can also check out examples directory.

Performance

react-container-query is using element-resize-detector in mainstream browsers and ResizeObserver in cutting edge browsers. It's completely event based, so no excessive code runs if no changes on element sizes.