- Notifications
You must be signed in to change notification settings - Fork49
📦 Modular responsive component
License
react-container-query/react-container-query
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
True modularity in styling responsive component.
npm i -D react-container-query
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.
Compare the hook style code with the original example fromhttps://github.com/react-container-query/react-container-query#containerquery-queryquery-initialsizewidth-height
- Native DOM element refers to
div,span, etc.
importReactfrom'react';import{useContainerQuery}from'react-container-query';constquery={'width-between-400-and-599':{minWidth:400,maxWidth:599,},'width-larger-than-600':{minWidth:600,},};constMyComponent=()=>{const[params,containerRef]=useContainerQuery(query);return<divref={containerRef}className={classnames(params)}>the box</div>;};
- If the container element we want to measure is a React component, and since we can't measure the size of React component itself, we can use
React.forwardRef. - The container React component must then forward the
refand set it on the actual native DOM element it renders (e.g,div,span, etc) - as seen in th example below
importReactfrom'react';import{useContainerQuery}from'react-container-query';constquery={'width-between-400-and-599':{minWidth:400,maxWidth:599,},'width-larger-than-600':{minWidth:600,},};constMyCustomWrapper=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<divref={ref}>{props.children}</div>});constMyComponent=()=>{const[params,containerRef]=useContainerQuery(query);return<MyCustomWrapperref={containerRef}className={classnames(params)}>the box</div>;};
- In this example,
<MyCustomWrapper />would forward thecontainerRefand set it on thedivelement it is using to wrap the children.
importReact,{Component}from'react';import{render}from'react-dom';import{ContainerQuery}from'react-container-query';importclassnamesfrom'classnames';constquery={'width-between-400-and-599':{minWidth:400,maxWidth:599},'width-larger-than-600':{minWidth:600,}};functionMyComponent(){/** * `params` in the children function will look like * { * 'width-between-400-and-599': true, * 'width-larger-than-600': false * } */return(<ContainerQueryquery={query}>{(params)=>(<divclassName={classnames(params)}>the box</div>)}</ContainerQuery>);};/** * This will generate following HTML: * <div></div> */render(<MyComponent/>,document.getElementById('app'));
props.childrenMust 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)initialSizeis an object with optionalwidthorheightproperty. 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 timeinitialSizewill be used as the size of the element.
importReact,{Component}from'react';import{render}from'react-dom';import{applyContainerQuery}from'react-container-query';importclassnamesfrom'classnames';constquery={'width-between-400-and-599':{minWidth:400,maxWidth:599},'width-larger-than-600':{minWidth:600,}};classContainerextendsComponent{render(){/** * `this.props.containerQuery` will look like * { * 'width-between-400-and-599': true, * 'width-larger-than-600': false * } */return<divclassName={classnames(this.props.containerQuery)}>the box</div>;}}constApp=applyContainerQuery(Container,query)/** * This will generate following HTML: * <div></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.
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.
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." (fromContainer 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 doesnot provide these CSS features.
Checkout CodePen
- Adjustable Sidebarhttp://codepen.io/daiweilu/pen/wMrrZM
- Responsive Component Layouthttps://codepen.io/daiweilu/pen/EXWRqx
You can also check outexamples directory.
react-container-query is usingelement-resize-detector in mainstream browsers andResizeObserver in cutting edge browsers. It's completely event based, so no excessive code runs if no changes on element sizes.
About
📦 Modular responsive component
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.