Why This Is Useful
Designing a Lightning Web Component that has to look right on a desktop, an iPad and an iPhone is a bit of a pain. Sometimes CSS media queries are enough, and sometimes you genuinely need your JavaScript to know what it’s running on so you can render something different entirely.
Good news: there’s a built in module for exactly this and it takes one line.
The Code
import { LightningElement } from 'lwc';
import FORM_FACTOR from '@salesforce/client/formFactor';
export default class DeviceAwareComponent extends LightningElement {
get isDesktop() {
return FORM_FACTOR === 'Large';
}
get isTablet() {
return FORM_FACTOR === 'Medium';
}
get isPhone() {
return FORM_FACTOR === 'Small';
}
}Import @salesforce/client/formFactor and you get back one of exactly three values:
Large – desktop
Medium – tablet
Small – phone
That’s the whole API. Three values, no configuration, nothing to set up.
Using It In Your Template
<template>
<template lwc:if={isPhone}>
<p>Compact view for the tiny screen crowd</p>
</template>
<template lwc:else>
<p>The full fat desktop experience</p>
</template>
</template>Because those getters are reactive properties, the template just works with them like any other value.
One Thing Worth Knowing
FORM_FACTOR is evaluated when the component loads and it doesn’t change afterwards. So if someone resizes their browser window from full screen down to something phone shaped, this value stays Large, because they’re still on a desktop.
That’s usually the behaviour you want, since “what device is this” and “how wide is the window right now” are different questions. If it’s really the window width you care about, that’s a job for CSS media queries or the SLDS responsive utility classes.
Use the form factor for genuine device decisions. Use CSS for layout.
Full details are in the LWC developer guide. Now go make your components behave themselves on mobile.
Get Coding With The Force Merch!!
We now have a redbubble store setup so you can buy cool Coding With The Force merchandise! Please check it out! Every purchase goes to supporting the blog and YouTube channel.
Get Shirts Here!
Get Cups, Artwork, Coffee Cups, Bags, Masks and more here!
Check Out More Coding With The Force Stuff!
If you liked this post make sure to follow us on all our social media outlets to stay as up to date as possible with everything!
Youtube
Patreon
Github
Facebook
Twitter
Instagram
Salesforce Development Books I Recommend
Advanced Apex Programming
Salesforce Lightning Platform Enterprise Architecture
Mastering Salesforce DevOps
Good Non-SF Specific Development Books:
Clean Code
Clean Architecture