@carbon/react
Version:
React components for the Carbon Design System
37 lines (31 loc) • 1.16 kB
JavaScript
/**
* Copyright IBM Corp. 2016, 2023
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
;
Object.defineProperty(exports, '__esModule', { value: true });
var React = require('react');
/**
* Listens to changes in a media query and returns whether it matches.
* @param mediaQuery - The media query to listen to. For example, `(min-width: 600px)`.
* @param defaultState - The initial state to return before the media query is evaluated. Defaults to `false`.
* @returns Whether the media query matches.
*/
const useMatchMedia = (mediaQuery, defaultState = false) => {
const [matches, setMatches] = React.useState(defaultState);
React.useEffect(() => {
const listener = event => {
setMatches(event.matches);
};
const mediaQueryList = window.matchMedia(mediaQuery);
mediaQueryList.addEventListener('change', listener);
setMatches(mediaQueryList.matches);
return () => {
mediaQueryList.removeEventListener('change', listener);
};
}, [mediaQuery]);
return matches;
};
exports.useMatchMedia = useMatchMedia;