Improve media queries
Closed this issue · 0 comments
There is no discussion tab activated for this repository, so I share my thoughts here.
I found this repo (thank you so much!) when i stumbled over a problem when using the orientation property of the MaterialUI Stepper component. The goal was to display a horizontal Stepper when the display width is less than xl (1536px), otherwise a vertical Stepper.
I got a very ugly layout shift when using a media query to evaluate the correct orientation by doing this:
const matchesDownXl = useMediaQuery(theme.breakpoints.down('xl'))
const orientation = matchesDownXl ? 'horizontal' : 'vertical';
The solution for that problem was to add a hint that measures the window width:
export const windowWidthHint = {
cookieName: 'CH-window-width',
getValueCode: 'window.screen.width',
// xl breakpoint: https://mui.com/material-ui/customization/breakpoints/
fallback: 1536,
transform: (value) => {
return parseInt(value, 10);
},
} as const satisfies ClientHint<number>;
With that hint I was able to level up my media queries by using the ssrMatchMedia
property of the useMediaQuery
-options:
const hints = useHints();
const matchesDownXl = useMediaQuery(theme.breakpoints.down('xl'), {
ssrMatchMedia: () => ({
matches: hints.windowWidth < theme.breakpoints.values.xl,
}),
});
Now the media query is evaluated correctly on the server and there are no more shifts anymore. :)
Are there any downsides with that approach? I would like to hear some opinions.