Breakpoint rendering in web components
Matt Levy
Posted on December 1, 2021
Tailoring a user experience for different devices can get complicated. There are many approaches to rendering a different view for mobile, tablet and desktop users.
This post presents a way to offer a tailored render for different breakpoints in the same component.
The benefit of this approach is useful when you need to render the same content components in an app and have them render a specific set of HTML based on viewport size.
Define the breakpoints
Firstly, the breakpoints need defining. This sets the viewport widths and the render function to use at this breakpoint.
const breakpointConfig = {
reactive: false,
breakpoints: {
992: { method: 'renderTablet' },
768: { method: 'renderMobile' },
1200: { method: 'renderDesktop' }
}
}
The reactive
property will make the component automatically re-render when the viewport width changes - this is optional.
Each breakpoint has a number key for the width followed by an object containing a method
to use at that viewport breakpoint.
The above config results in the following media query list.
only screen and (max-width: 768px)
only screen and (min-width: 769px) and (max-width: 992px)
only screen and (min-width: 1201px)
Component usage
Using the above breakpoint config, a component can be created with render methods for each breakpoint.
import { createCustomElement, withBreakpointRender } from 'https://cdn.skypack.dev/ficusjs@3'
import { html, renderer } from 'https://cdn.skypack.dev/@ficusjs/renderers@3/uhtml'
createCustomElement(
'breakpoint-component',
withBreakpointRender(breakpointConfig, {
renderer,
renderTablet () {
return html`<span>Breakpoint render tablet</span>`
},
renderMobile () {
return html`<span>Breakpoint render mobile</span>`
},
renderDesktop () {
return html`<span>Breakpoint render desktop</span>`
}
})
)
To view the component in action see this Codepen - https://codepen.io/ducksoupdev/pen/WNZbWbq?editors=1010
Try resizing the Codepen panel!
Summary
Conditionally rendering HTML based on the viewport width can be a powerful way to offer a tailored user experience.
Some examples of using this approach are:
- Render a table on desktop and list view on mobile
- Conditionally hide functionality on smaller screens
- Show tabbed navigation on mobile and sidebar on desktop
- Maintain state within a component presented in different ways
For more documentation visit https://docs.ficusjs.org/extending-components/with-breakpoint-render/
Try it in your next project!
Posted on December 1, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
September 25, 2024
January 5, 2023