Skip to main content

useMedia

window.matchMedia() can be used to determine if the document matches the media query string. This hook utilizes this API to work with responsive web design inside React lifecycle programmatically.

ColumnCalculator.jsx
import { useMedia } from "@trakas/react";
export function ColumnCalculator() {
const columnCount = useMedia(
// Media queries
["(min-width: 1500px)", "(min-width: 1000px)", "(min-width: 600px)"],
// Column counts (relates to above media queries by array index)
[5, 4, 3],
// Default column count
2
);
return <div>Column count: {columnCount}</div>;
}

Options#

const queryValue = useMedia(queries, values, defaultValue);
  • queries: string[]
  • values: T[]
    • Required
    • The array of values corresponding to queries
  • defaultValue: T
    • Required
    • The fallback value when there is no query is matched

Returns#

  • queryValue: T
    • The value of the first matched query
note

Only the value of the first matched query is returned. It would be best to use the same attribute for all queries to get an effective result.