#Media query hook

3 messages · Page 1 of 1 (latest)

viscid oar
terse streamBOT
#

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.

For more information, you can refer to the Astro 0.18 Release blog post (https://astro.build/blog/astro-018#responsive-partial-hydration) and the Github issue (https://github.com/withastro/astro/issues/514) where this feature was proposed.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: