DEV Community

Matt Levy for Ficus

Posted on

Breakpoint rendering in web components

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' }
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Component usage

Using the above breakpoint config, a component can be created with render methods for each breakpoint.

import { createCustomElement, withBreakpointRender } from ''
import { html, renderer } from ''

  withBreakpointRender(breakpointConfig, {
    renderTablet () {
      return html`<span>Breakpoint render tablet</span>`
    renderMobile () {
      return html`<span>Breakpoint render mobile</span>`
    renderDesktop () {
      return html`<span>Breakpoint render desktop</span>`
Enter fullscreen mode Exit fullscreen mode

To view the component in action see this Codepen -

Try resizing the Codepen panel!


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

Try it in your next project!

Top comments (0)