Tag Archives: Component Find

Difference Between Component.get() And Component.find() in Salesforce Lightning

component.find() :

  • It returns the Aura.Component instance(s) by its local ID.
  • If the Aura.Component local ID is unique, it returns the component and if there are multiple Aura.Component with the same local ID, it returns an array of the components.
  • Syntax: component.find("auraid");

component.get() :

  • It is associated with Component attributes and returns the referenced component attribute value.
  • Syntax: component.get(String key);

Lightning Component:

<aura:component >
    <aura:attribute name="firstName" type="String"/>
    <aura:attribute name="lastName" type="String"/>
    
    <div class="slds-m-around--xx-large">
        <div class="container-fluid">
            <div class="form-group">
                <lightning:input name="fName" aura:id="fName" type="text" required="true" maxlength="50" label="First Name" value="{!v.firstName}" />
            </div>
            <div class="form-group">
                <lightning:input name="lName" aura:id="lName" type="text" required="true" maxlength="50" label="Last Name" value="{!v.lastName}" />
            </div>
            <br/> 
            <lightning:button variant="brand" label="Submit" onclick="{!c.handleSubmit}" /> 
        </div>
    </div>
</aura:component>

Lightning JS Controller:

({
    handleSubmit : function(component, event, helper) {
        //Find component and get value using component.find();
        var fNameCmp = component.find("fName");
        var lNameCmp = component.find("lName");
        
        console.log('First Name : ' + fNameCmp.get("v.value"));
        console.log('Last Name : ' + lNameCmp.get("v.value"));
        
        //Get attribute value using component.get();
        var fNameAttValue = component.get("v.firstName");
        var lNameAttValue = component.get("v.lastName");
        
        console.log('First Name : ' + fNameAttValue);
        console.log('First Name : ' + lNameAttValue);
    } 
})