In this blog I will show you how you can access device form factor and configure your component accordingly in Salesforce.
You can access the form factor by importing below module
1 | import FORM_FACTOR from '@salesforce/client/formFactor' |
FORM_FACTOR can return below values based on device.
Large - Desktop/Laptop
Medium - Tablet
Small - Mobile Device
To manage component rendering based on form factor you can use two ways -
- Use a parent LWC and based on FORM_FACTOR value in connectedCallback() maintain the rendering.
- Configure the FORM_FACTOR in js-meta.xml file.
Please check complete code below :
HTML
1 2 3 4 5 6 7 | <template> <lightning-card title="Form Factor"> <div class="slds-var-m-around_medium"> <b>You are viewing it from {deviceType}</b> </div></lightning-card > </template> |
JS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import { LightningElement } from "lwc"; import FORM_FACTOR from "@salesforce/client/formFactor"; export default class ClientFormFactor extends LightningElement { deviceType; connectedCallback() { if (FORM_FACTOR === "Large") { this.deviceType = "Desktop/Laptop"; } else if (FORM_FACTOR === "Medium") { this.deviceType = "Tablet"; } else if (FORM_FACTOR === "Small") { this.deviceType = "Mobile"; } } } |
meta.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?xml version="1.0" encoding="UTF-8"?> <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata"> <apiVersion>54.0</apiVersion> <isExposed>true</isExposed> <targets> <target>lightning__AppPage</target> <target>lightning__RecordPage</target> <target>lightning__HomePage</target> </targets> <targetConfigs> <targetConfig targets="lightning__AppPage"> <supportedFormFactors> <supportedFormFactor type="Small" /> </supportedFormFactors> </targetConfig> </targetConfigs> </LightningComponentBundle> |
Note : Once a component is in use on a Lightning page, you can only increase the supported form factors for the component, not decrease them.
Output
Checkout complete video below
0 Comments