How do I conditionally render a component in Next.js based on screen width?

Clock Icon

asked about 1 year ago

Message Icon

1

Eye Icon

68

I am building a responsive dashboard in Next.js and I want to show a different layout on mobile and desktop. I know that CSS handles responsiveness, but I want to render a completely different component based on screen width in my React component logic. I tried using window.innerWidth but it does not work reliably during SSR. What is the proper way to handle this?

1 Answer

Since window is not available during server-side rendering, you should use a hook that only runs on the client. Here is one way to do it:

1import { useEffect, useState } from 'react';
2
3const useIsMobile = () => {
4 const [isMobile, setIsMobile] = useState(false);
5
6 useEffect(() => {
7 const checkWidth = () => setIsMobile(window.innerWidth <= 768);
8 checkWidth();
9 window.addEventListener('resize', checkWidth);
10 return () => window.removeEventListener('resize', checkWidth);
11 }, []);
12
13 return isMobile;
14};
1import { useEffect, useState } from 'react';
2
3const useIsMobile = () => {
4 const [isMobile, setIsMobile] = useState(false);
5
6 useEffect(() => {
7 const checkWidth = () => setIsMobile(window.innerWidth <= 768);
8 checkWidth();
9 window.addEventListener('resize', checkWidth);
10 return () => window.removeEventListener('resize', checkWidth);
11 }, []);
12
13 return isMobile;
14};

Use it like this:

1const MyComponent = () => {
2 const isMobile = useIsMobile();
3 return isMobile ? <MobileLayout /> : <DesktopLayout />;
4};
1const MyComponent = () => {
2 const isMobile = useIsMobile();
3 return isMobile ? <MobileLayout /> : <DesktopLayout />;
4};

1

Write your answer here