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 />;
}
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
}
Usage:
<Responsive
mobile={<MobileComponent />}
desktop={<DesktopComponent />}
/>
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 />
.
Top comments (0)