Inspired by this blog post on dev.to.
To get the current screen size, you can use the useBreakpoints
hook:
// src/MyComponent.tsx
import { useBreakpoints } from '~/hooks/useBreakpoints';
export default function MyComponent() {
const { current } = useBreakpoints();
return (
<div>
<h1>
My current viewport size is: <span>{current}</span>
</h1>
</div>
);
}
Or better yet, use the Breakpoint
component to render nested components conditionally:
// src/MyComponent.tsx
import Breakpoint from '~/components/Breakpoint';
import MobileLayout from '...';
import Sidebar from '...';
import Content from '...';
export default function MyComponent() {
return (
<div>
<Breakpoint size='xs'>
{/* Not much space here, so render mobile layout */}
<MobileLayout />
</Breakpoint>
<Breakpoint size='md'>
{/* Enough space for a sidebar and some content */}
<Sidebar />
<Content />
</Breakpoint>
</div>
);
}
The following breakpoints are handled by this example:
xs
(<=640px
)sm
(between641px
and768px
)md
(between769px
and1024px
)lg
(>=1025px
)