1

I have a huge Aura Component that I must convert into a Lightning Web Component. I need some help to start develop this new component.

One part of the Controller code:

({  
    doInit: function (component, event, helper) {
        component.set('v.showSaveSuccess', false);

        helper.ondoInitRender(component);
        helper.addScroll(component);
        if (event.getParam('newRequestReceived')) {
            component.set('v.cmpCreated', true);
        }
        helper.getFilters(component);
    },

    getProducts: function (component, event, helper) {
        helper.getProducts(component);
    },

    handleApplicationEvent: function (component, event, helper) {
        helper.handleApplicationEventHelper(component, event);
        helper.buildData(component);
    },

    selectAllFunc: function (component, event, helper) {
        helper.selectAllHelper(component);
    },

    changeVal: function (component, event, helper) {
        var fieldname = event.getSource().get('v.name');
        var name = fieldname.slice(9);
        var value = event.getSource().get('v.value');

        if (value != null && value != '') {
            helper.changeValHelper(component, name);
        }
    }
    ...
})

A part of the Helper code:

({
    getFilters: function (component) {
        this.showSpinner(component);
        var action = component.get("c.initFilters");
        var arrExisting = !$A.util.isUndefinedOrNull(component.get("v.productsAlreadyInCart")) ? component.get("v.productsAlreadyInCart") : [];
        action.setParams({ 
            oppId : component.get("v.recordId"),
            doInit : true,
            productsAlreadyInCart : JSON.stringify(arrExisting),
            existingFiltersStr : null
        });
        action.setCallback(this, function(response) {
            if (component.get('v.cmpCreated')) {
                window.parent.location.reload(true);
            } else {
                this.hideSpinner(component);
            }
            var state = response.getState();
            if (state === "SUCCESS") {
                if(!$A.util.isUndefinedOrNull(response.getReturnValue().validatePage)) {
                    this.navigateToComponentHelper(component, response.getReturnValue().validatePage);
                } else {
                    var vals = [$A.get("$Label.c.Label_CreateOpportunity"), 
                    $A.get("$Label.c.Label_ProductSearch"), 
                    $A.get("$Label.c.Sopping_cart_title"), 
                    $A.get("$Label.c.Label_AdditionalInformation")];
                    component.set("v.indicatorElements", vals);
                    component.set("v.filterObjs", response.getReturnValue().filters);
                    component.set("v.mainObj", response.getReturnValue());
                    component.set("v.triggerGetProds", true);

                    if (localStorage.getItem("showSaveSuccess") != null) {
                        component.set('v.showSaveSuccess', true);
                        var mainObj = component.get("v.mainObj");

                        mainObj.messageType = 'success';
                        mainObj.messageToDisplay = $A.get("$Label.c.Saved_Date");

                        component.set("v.mainObj", mainObj);
                    }

                    localStorage.removeItem("showSaveSuccess")
                }
            } else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        this.showToast($A.get("$Label.c.ErrorMessage"), errors[0].message);
                    }
                } else {
                    this.showToast($A.get("$Label.c.ErrorMessage"), $A.get("$Label.c.UnknownError"));
                }
            }
        });
        $A.enqueueAction(action);
    }
    ...
})

The Handler code:

({
    afterRender: function (component, helper) {
        this.superAfterRender();
        if($A.get("$Browser.isIPad")) {
            document.querySelector(".slds-max-medium-table--stacked-horizontal").classList.add('tableIpadPro');
            document.querySelector(".slds-max-medium-table--stacked-horizontal thead").classList.add('theadIpadPro');
            var arr = document.getElementsByTagName("tr");

            for(var a = 0; a < arr.length; a++){
                arr[a].classList.add('trIpadPro');
            }

            arr = document.getElementsByTagName("td");

            for(var a = 0; a < arr.length; a++){
                arr[a].classList.add('tdIpadProSecondary');
            }

            arr = document.getElementsByTagName("td");

            for(var a = 0; a < arr.length; a++){
                arr[a].classList.add('tdBefore');
            }
        }
    }
})

Please, I need help to start converting from Aura to LWC.

Thanks in advance, Renato

1
  • 2
    Trailhead would be the best place for you to start and understand how LWC works, so you can get a better grasp on what needs to be done. there are also docs available to help you understand how to migrate your components. I'd suggest you spend some time learning the ropes of LWC instead of posting "how to" questions here. Thanks
    – glls
    Feb 14, 2022 at 18:06

2 Answers 2

1

There is Migrate Aura Components to Lightning Web Components which contains a lot of information and sub-pages specific to migrating specific parts of a component.

Some important notes/quotes from the documentation

The programming model for Lightning Web Components is fundamentally different than the model for Aura components. Migrating a component is not a line-by-line conversion, and it's a good opportunity to revisit your component's design. Before you migrate an Aura component, evaluate the component’s attributes, interfaces, structures, patterns, and data flow.

You've pasted your aura component, but that's not the only thing to consider.

  • What is the component doing?
  • Where is the component used?

Answers to the above questions may yield design changes or strategy changes.


You've only shared your controller/handler, but Migrate Markup contains helpful info on converting specific usages in Aura into LWC. You'll find examples where it's very similar and others where's it's different. As an example, aura had its attributes defined in the component <aura:attribute> while in LWC it'd be a javascript property.

For code examples, if you view aura components in the documentation (ex. Button), there's a button in the upper right to View as Lightning Web Component. If that button is greyed out, it means there's a different component used in LWC that solves a similar need or there isn't one.

enter image description here


Based on what you shared, you'll be focusing on JavaScript.

For doInit, there's Migrate Initializers

Replace an init event handler in an Aura component with the standard JavaScript connectedCallback() method in a Lightning web component.

We use the init event in an Aura component to initialize a component after component construction but before rendering.

({
    doInit: function(cmp) {
        // initialize component
    }
})

becomes

// mySampleInit.js
import { LightningElement } from 'lwc';
export default class MySampleInit extends LightningElement {
    connectedCallback() {
        // initialize component
    }
}

For calls to apex, there's imperative apex and wire apex methods to components. Wire will cache the result so it's use-case is typically one where you don't want to be re-calling the server for updated info. That decision depends on what your call is doing.

A conversion of that may look like so:

var action = cmp.get("c.yourApexMethod");
action.setParams({ parameterNameInMethod : cmp.get("v.yourVariableInComponent") });

action.setCallback(this, function(response) {
    var state = response.getState();
     if (state === "SUCCESS") {
         //do logic on response
   ...
getFilters() {
    yourApexMethod({ parameterNameInMethod: this.yourVariableInComponent })
        .then((result) => {
           //do logic with result
        })
}

For the other methods, it may end up being very similar. Accessing elements the component owns is a similar mechanism and just a syntax difference

this.template.querySelector();
this.template.querySelectorAll();

That exercise is generally just figuring out the syntax differences.


There's a lot of info/documentation, but I'll call out one other major difference to note: Data Binding Behavior

Lightning Web Components The data binding between components for property values is one-way.

To communicate down from a parent component to a child component, set a property or call a method on the child component.

To communicate up from a child component to a parent component, send an event.

0

You might want to try a converter I built - https://aura-to-lwc.herokuapp.com - although I do not attempt to convert Aura Custom Renderers because I don't see a direct equivalent in LWC.

You must log in to answer this question.

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