import React = require('react'); import ReactDOM = require('react-dom'); import matchQueries from 'container-query-toolkit/lib/matchQueries'; import {Props, State, Params, Query, Size} from './interfaces'; import ContainerQueryCore from './ContainerQueryCore'; /** * * {(params) => { *
* }} *
*/ export class ContainerQuery extends React.Component { private cqCore: ContainerQueryCore | null = null; constructor(props: Props) { super(props); this.state = { params: props.initialSize ? matchQueries(props.query)(props.initialSize) : {}, }; } componentDidMount() { this.cqCore = new ContainerQueryCore(this.props.query, (params) => { this.setState({params}); }); this.cqCore.observe(ReactDOM.findDOMNode(this)); } componentDidUpdate() { this.cqCore!.observe(ReactDOM.findDOMNode(this)); } componentWillUnmount() { this.cqCore!.disconnect(); this.cqCore = null; } render() { return this.props.children(this.state.params); } } /** * applyContainerQuery(BoxComponent, query, initialSize); */ export type Component = React.ComponentClass | React.StatelessComponent; export interface QueryProps { containerQuery: Params; }; export function applyContainerQuery( Component: Component, query: Query, initialSize?: Size ): React.ComponentClass { return class ContainerQuery extends React.Component { static displayName: string = Component.displayName ? `ContainerQuery(${Component.displayName})` : 'ContainerQuery'; private cqCore: ContainerQueryCore | null = null; constructor(props: T) { super(props); this.state = { params: initialSize ? matchQueries(query)(initialSize) : {}, }; } componentDidMount() { this.cqCore = new ContainerQueryCore(query, (params) => { this.setState({params}); }); this.cqCore.observe(ReactDOM.findDOMNode(this)); } componentDidUpdate() { this.cqCore!.observe(ReactDOM.findDOMNode(this)); } componentWillUnmount() { this.cqCore!.disconnect(); this.cqCore = null; } render() { return ( ); } }; }