#window.matchMedia('(orientation: portrait)')
1 messages · Page 1 of 1 (latest)
Hi @fervent sorrel. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
In Next.js, the window object is not available in server components. This is because server components are rendered on the server where the window object, which is a browser-specific global object, does not exist.
If you need to use the window object, you should do so within a client component or use a lifecycle method like useEffect that runs on the client side. Here's an example of how you can use window in a client component:
import { useEffect, useState } from 'react';
function MyComponent() {
const [isPortrait, setIsPortrait] = useState(false);
useEffect(() => {
if (typeof window !== 'undefined') {
setIsPortrait(window.matchMedia('(orientation: portrait)').matches);
}
}, []);
// rest of your component
}
In this example, we're using the useEffect hook to set the isPortrait state only on the client side where the window object is available. The typeof window !== 'undefined' check ensures that this code will not run on the server where window is not defined.
Remember, if you're using the new App Router introduced in Next.js 13, you can continue to use client components alongside server components. The App Router can coexist with the existing pages directory for incremental adoption (source (https://vercel.com/templates/next.js/app-directory)).