DEV Community

Sol Lee
Sol Lee

Posted on

Displaying different UI for mobile and desktop screens

Summary

Create <Responsive /> component to display different UI components for mobile and desktop screens

Limitations

As frontend devs, we often need to display different UI components for small screens (mobile) and larger screens (tablet, PC..).

For example, we may be required to render a bottomsheet for mobile, but a modal for PCs.

We can use media-query to set the breakpoint for each device and use a flag variable such as isMobile to render each component:

export default function Responsive() {
  const isMobile = useMediaQuery('(max-width: 768px)'); // Breakpoint for mobile

  return isMobile ? <MobileComponent /> : <DesktopComponent />;
}
Enter fullscreen mode Exit fullscreen mode

What are the limitations of this code?

Let's see it from the maintanance point of view.

For now, we are just required to handle with two types: mobile and non-mobile. However, what if in the future we are required to display different UIs for watch or tvOS? We'll probably have to use switch-case, which is totally fine but is there any simpler solution?

Also, the <Responsive/> component described above is not so fit for reusability. In other words, what if we want to use components other than MobileComponent and DesktopComponent?

Create a universal component for responsiveness

After some ideation, we can rewrite our code:

export default function Responsive() {
  const isMobile = useMediaQuery('(max-width: 768px)'); // Breakpoint for mobile

  return isMobile ? mobile : desktop
}
Enter fullscreen mode Exit fullscreen mode

Usage:

<Responsive 
  mobile={<MobileComponent />} 
  desktop={<DesktopComponent />} 
/>
Enter fullscreen mode Exit fullscreen mode

This way, we can reuse the <Responsive /> component by simply passing the respective component as props (mobile, desktop).

Also, isMobile ? mobile : desktop looks much simpler than isMobile ? <MobileComponent /> : <DesktopComponent />.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay