Does Astro provide any solution similar to useMediaQuery https://usehooks-ts.com/react-hook/use-media-query
so I can render components based on the screen size?
3 messages · Page 1 of 1 (latest)
Does Astro provide any solution similar to useMediaQuery https://usehooks-ts.com/react-hook/use-media-query
so I can render components based on the screen size?
Hi @viscid oar. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Yes, Astro provides a solution to render components based on screen size. This is achieved through the use of the client:media directive and CSS media queries.
You can add the client:media directive to a component and it will only hydrate once the media condition is met. This means that you can avoid loading mobile-only code on non-mobile devices, and vice versa.
Here's an example of how you can use it:
---
import Nav from '../components/Nav.jsx';
---
<Nav client:media="(max-width: 768px)" />
In this example, the Nav component will only be loaded if the screen width is 768px or less.
Astro also allows you to define your media queries in a common place for reusability. For example:
src/queries.js
export const PHONE = '(max-width: 768px)';
src/pages/index.astro
---
import Nav from '../components/Nav.jsx';
import {PHONE} from '../queries.js';
---
<Nav client:media={PHONE} />
In this example, the PHONE constant is defined in a separate file and imported into the Astro component. The Nav component will only be loaded if the screen width matches the PHONE media query.
This feature is part of Astro's commitment to minimizing the unnecessary JavaScript that you send to your users.