3

I want to create a lightning component when run in desktop show one style when run in mobile show another style. Can I implementation this?

Thanks for your help and advice.

Best wishes, Lee

3 Answers 3

8

At least you can access the form factor of the hardware the browser is running on in LWC:

import formFactorPropertyName from '@salesforce/client/formFactor';

formFactorPropertyName — a name that refers to the form factor of the hardware running the browser. Possible values are:

  • Large — A desktop client.
  • Medium — A tablet client.
  • Small — A phone client.

Depending on that value you can customize your styles, render components conditionally, etc. For instance you will be able to see this block only at desktop form factor:

<!--test.html-->
<template>
    <div if:true={isDesktop}>
        I'm running in a desktop client
    </div>
</template>
// test.js
import FORM_FACTOR from '@salesforce/client/formFactor';

export default class Test extends LightningElement {

    get isDesktop() {
        return FORM_FACTOR === 'Large';
    }
}

For Aura Component you can access $Browser global value provider

<aura:component>
    <aura:if isTrue="{!$Browser.formFactor === 'Desktop'">
        I'm running in a desktop client
    </aura:if>
</aura:component>
2
  • Hi Oleh, Thank you for your advice. It's work for me. Best wishes, Lee
    – GhostLee
    Commented Aug 5, 2020 at 5:20
  • You're welcome, Lee. Commented Aug 5, 2020 at 6:43
1

This is not exactly the answer but hopefully it can guide you to it. Try to explore the salesforce lightning design system. You won't be able to control if its desktop or mobile, but you'll be able to adapt the design based on the size of the screen ( which in my opinion can already give you an idea which type it is)

here is a link to help you with the Slds-size concept: https://www.lightningdesignsystem.com/utilities/sizing/

0

If your files get long and bulky, using if:true in LWC is not going to be very friendly. If you're dealing with LWC, I recommend using multiple templates and use the retrieved form factor to determine which to render. Developer documentation for using multiple templates is available here.

Essentially, you'll make two additional HTML files for the different templates (and CSS if applicable), import them, and in the render() function determine which to use.

Modifying their example JS, for formFactor (assuming you'd use templateOne for desktop and templateTwo for mobile), it would look something like this:

import { LightningElement } from 'lwc';
import FORM_FACTOR from '@salesforce/client/formFactor';
import templateOne from './templateOne.html';
import templateTwo from './templateTwo.html';

export default class MiscMultipleTemplates extends LightningElement {
     render(){
         return FORM_FACTOR === 'Small' ? templateTwo : templateOne;
     }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .