Detect Device Form Factors in lwc & change the component behavior

Telegram logo Join our Telegram Channel

The lightning web components are now device-aware. You can detect the device form factor using the standard @salesforce/client/formFactor module in the LWC framework.

To use this module you need to import it like below.

import FORM_FACTOR from '@salesforce/client/formFactor'

The FORM_FACTOR can have below values based on the type of the device.

  • Large - If the device is a desktop.
  • Medium - If the device is a tablet.
  • Small - A phone client


How to use the form factor in your component?

You can use the form factor to get the create defaults of the record for a particular device form factor.
As per the standard documentation, you can use this as mentioned in this post: Access Client Form Factor
But I am going to give you another example of this.


Use Case

Let's say you have a Lightning web component which is displays a particular section only if the opening device is a mobile device. Also there a block of a code that you need to execute only for the mobile devices.


Sample Code


formFactorDemo.js

import { LightningElement } from 'lwc';
import FORM_FACTOR from '@salesforce/client/formFactor';
export default class FormFactorDemo extends LightningElement {

    connectedCallback() {
        console.log('The device form factor is: ' + FORM_FACTOR);
    }

    get message (){
        switch(FORM_FACTOR) {
            case 'Large':
            return 'You are on desktop';
            case 'Medium':
            return 'You are on tablet';
            case 'Small':
            return 'You are on mobile';
            default:
        }
    }
}


formFactorDemo.html

<template>
    <lightning-card title="Form Factor Demo">
        <div class="slds-var-p-around_medium">
            <div>Message : {message}</div>
        </div>
    </lightning-card>
</template>


The Output



Final Words

With this API we can change the look, feel, and behaviour of the components based on the device form factor. We saw how we can execute different code based on the device type. For the demo purpose, I simply used the switch case statement with a different for each device type, but you can definitely do more than that.

I hope this has helped you. Thank you for reading!
2 comments:

Hi there, comments on this site are moderated, you might need to wait until your comment is published. Spam and promotions will be deleted. Sorry for the inconvenience but we have moderated the comments for the safety of this website users. If you have any concern, or if you are not able to comment for some reason, email us at rahul@forcetrails.com