useMediaQuery Hook
Introduction
A custom React Hook for handling media queries.
Play
Usage
import { useMediaQuery } from "@cannonui/reacthooks";
const TestUseMediaQuery = () => {
const isMatch = useMediaQuery("(max-width: 468px)");
return (
<div>is match max width 468px: {isMatch ? "matched" : "not match"}</div>
);
};
export default TestUseMediaQuery;
Return Value
The hook returns a boolean value indicating whether the media query matches the current viewport or not.
Parameters
Name | Type | Description |
---|---|---|
query | string | The media query to be evaluated. |
Features
- Handles media queries and provides a boolean value indicating whether the query matches the current viewport.
- Supports server-side rendering and client-side synchronization of media query changes.
Example
In this example, we have a component called TestUseMediaQuery
that uses the useMediaQuery
Hook to check if the viewport height is less than or equal to 468 pixels. The useMediaQuery
Hook handles the media query and provides the isMatch
boolean value, which indicates whether the query matches the current viewport.
Use Scenario
The useMediaQuery
Hook is useful in scenarios where you want to conditionally render components or apply styles based on the viewport size. For example, you might want to show different layouts or components for different screen sizes or orientations. By using the useMediaQuery
Hook, you can easily handle media queries and make your React components responsive to different viewport conditions.