UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

81 lines (80 loc) 2.08 kB
"use client"; import React from 'react'; import { isTrue } from "./component-helper.js"; import Context from "./Context.js"; import { makeMediaQueryList, createMediaQueryListener, onMediaQueryChange, isMatchMediaSupported } from "./MediaQueryUtils.js"; export { onMediaQueryChange }; export default class MediaQuery extends React.PureComponent { static contextType = Context; state = { match: null, mediaQueryList: null }; constructor(props, context) { super(props); if (!isMatchMediaSupported() && isTrue(props.matchOnSSR)) { this.state.match = true; } if (isMatchMediaSupported()) { const { query, when, not } = props; const { disabled, correctRange = true, log } = props; this.state.mediaQueryList = makeMediaQueryList({ query, when, not }, context?.breakpoints, { disabled, correctRange, log }); if (this.state.mediaQueryList?.matches) { this.state.match = true; } } } componentDidMount() { if (isMatchMediaSupported()) { this.bindListener(); } } componentWillUnmount() { if (this.listener) { this.listener(); this.listener = null; } } componentDidUpdate(props) { if (this.props.query !== props.query || this.props.when !== props.when || this.props.not !== props.not) { const mediaQueryList = makeMediaQueryList(this.props, this.context.breakpoints); this.setState({ match: mediaQueryList?.matches, mediaQueryList }, this.bindListener); } } bindListener = () => { this.componentWillUnmount(); if (this.state.mediaQueryList) { this.listener = createMediaQueryListener(this.state.mediaQueryList, match => { this.setState({ match }); }); } }; render() { const { children } = this.props; return React.createElement(React.Fragment, null, this.state.match ? children : null); } } //# sourceMappingURL=MediaQuery.js.map