Skip to content

A simple proof-of-concept using custom hooks to render components based on the browser's viewport size.

Notifications You must be signed in to change notification settings

nick-cheatwood7/media-query-components

Repository files navigation

⚛️ Media Query Components

Inspired by this blog post on dev.to.

Usage

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 (between 641px and 768px)
  • md (between 769px and 1024px)
  • lg (>= 1025px)

About

A simple proof-of-concept using custom hooks to render components based on the browser's viewport size.

Topics

Resources

Stars

Watchers

Forks