Skip to content
📦 Modular responsive component
JavaScript TypeScript Shell
Branch: master
Clone or download
pixelbandito Merge pull request #86 from react-container-query/remove-refs-to-old-…
…repo-path

Fix CircleCI badge, update package links to use github organization in path
Latest commit d878764 Jan 21, 2020
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.circleci Remove extraneous key filters Jan 21, 2020
config Stop using broken Safari 11 / Mac OS X 10.12 pair Jan 21, 2020
examples Revert "Fixes #78: Use UNSAFE_ prefix for deprecated React lifecycle … Jan 8, 2020
scripts Jesstelford default values (#52) Mar 6, 2017
src
test Add test May 10, 2017
.babelrc
.eslintrc.yml Update dependencies May 10, 2017
.gitignore Fix parsing of decimal places Jul 16, 2016
.npmrc Learning to set up CircleCI Jan 21, 2020
.nvmrc
CONTRIBUTION.md Improve contribution guide Jul 24, 2016
README.md
gulpfile.js Refactor to use element-resize-detector Jul 13, 2016
karma.conf.js Upgrade all deps, fix build and test Jan 10, 2018
package-lock.json Learning to set up CircleCI Jan 21, 2020
package.json Remove references to old repo path with d6u's personal github username Jan 21, 2020
tsconfig.json Learning to set up CircleCI Jan 21, 2020
tslint.json Refactor to use element-resize-detector Jul 13, 2016

README.md

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

I am providing code in this repository to you under an open source license. Because this is my personal repository, the license you receive to my code is from me and not from my employer (Facebook).

API

<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

  • props.children

    Must be a function to return a single or an array of React elements. The function will be invoked with params, which is a key-value pair where keys are class names, values are booleans to indicate if that class name's constraints are all satisfied.

  • props.query

    "query" is key-value pairs where keys are the class names that will be applied to container element when all constraints are met. The values are the constraints.

  • props.initialSize? (optional)

    initialSize is an object with optional width or height property. Because the limitation on how size is computed based on underlying element, in the initial rendering pass, we don't have the size info (because element must be in the DOM have a valid size). At this time initialSize will be used as the size of the element.

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.

You can’t perform that action at this time.