Tag: JS Controller

  • What is the Search Box In Aura Component? | The Developer Guide

    What is the Search Box In Aura Component? | The Developer Guide

    A search box in an Aura component is a user interface element that allows users to input text and search for relevant information within the component or its associated data. In Aura, the search box can be implemented using the <lightning:input> component with the type=”search” attribute. This component provides a text input field along with a search icon that can be used to initiate the search. 

    When a user types in the search box and clicks the search icon or presses enter, the component can execute a server-side controller action or a client-side JavaScript function to retrieve and display the search results. The search functionality can be customized to match the requirements of the component, such as searching based on specific fields or filters. 

    Overall, the search box is a common UI element used in many Aura components to allow users to quickly find the data they need. 

    Component: 

    <aura:component controller="searchAccountController" > 
        <aura:attribute name="keywordHolder" type="string" />   
        <aura:attribute name="accountList" type="list" />   
        <lightning:input name="AccountSearch"  label="Enter Account Name" value="{!v.keywordHolder}"/>   
        <lightning:button label="Search Account" onclick="{!c.findAccount}" /> 
        <aura:iteration var="acc" items="{!v.accountList}" >    
        {!acc.Name} 
        {!acc.type} 
        </aura:iteration>  
    </aura:component>

    dont miss out iconDon’t forget to check out: Use Aura Component in Screen Flow | Salesforce Flow Builder Tutorial

    Controller:  

    ({ 
     findAccount : function(component, event, helper) {  
            var action=component.get('c.fetchAccount'); 
            action.setParams({ 
                searchKeyWord : component.get("v.keywordHolder")          
            });           
            action.setCallback(this,function(response){           
                var state=response.getState(); 
                var response1=response.getReturnValue(); 
                if(state==="SUCCESS") 
                { 
                    component.set("v.accountList",response1); 
                }          
            }); 
            $A.enqueueAction(action); 
     } 
    })

    Apex Controller:  

    public class searchAccountController { 
    @AuraEnabled 
     public static List < account > fetchAccount(String searchKeyWord) { 
      String searchKey = searchKeyWord + '%'; 
      List < Account > returnList = new List < Account > (); 
      List < Account > lstOfAccount = [select id, Name, Type, Industry, Phone, Fax from account where Name LIKE: searchKey limit 1]; 
      for (Account acc: lstOfAccount) { 
       returnList.add(acc); 
      } 
      return returnList; 
     } 
    }

    dont miss out iconCheck out another amazing blog by Narendra Kumar here: How to Send Emails Using Lightning Web Component (LWC)?

    Output: 

  • What are Aura Components in Salesforce? | The Ultimate Guide

    What are Aura Components in Salesforce? | The Ultimate Guide

    The Lightning Component framework may be a UI framework for developing web apps for mobile and desktop devices. It’s a contemporary framework for building single-page applications with dynamic, responsive user interfaces for Lightning Platform apps. It uses JavaScript on the client side and Apex on the server side. 

    The Lightning Component framework is a framework for developing web apps. 

    Creating and Editing Aura Components

    1. Select File | New | Lightning Component to create an Aura component. 
    2. In the New Lightning Bundle panel, enter helloWorld for the component name.
    3. Click Submit

    Your component markup should look like the following: 

    What is a Component? 

    A component is a bundle that includes a definition resource, written in markup, and may include additional, optional resources like a controller, stylesheet, and so on. 

    A resource is sort of like a file but stored in Salesforce rather than on a file system. 

    There are the opening and closing <aura:component> tags, with some static HTML in between.  

    A bundle is sort of like a folder. It groups the related resources into a single component. Resources in a bundle are auto-wired together via a naming scheme for each resource type. Auto-wiring just means that a component definition can reference its controller, helper, etc., and those resources can reference the component definition. They are hooked up to each other (mostly) automatically.

    dont miss out iconDon’t forget to check out: Use Aura Component in Screen Flow | Salesforce Flow Builder Tutorial

    What is an App? 

    • An app uses <aura:application> tags instead of <aura:component> tags. 
    • Only an app has a Preview button in the Developer Console. 

    What Are Apps For?

    • When writing markup, you can add a component to an app, but you can’t add an app to another app, or an app to a component. 
    • An app has a standalone URL that you can access while testing, and which you can publish to your users. We often refer to these standalone apps as “my.app.” 
    • You can’t add apps to Lightning Experience or the Salesforce app—you can only add components. After the last unit this might sound weird; what exactly do you add to the App Launcher, if not an app? What you add to App Launcher is a Salesforce app, which wraps up an Aura component, something defined in a <aura:component>. An Aura components app—that is, something defined in a <aura:application> —can’t be used to create Salesforce apps. A bit weird, but there it is. 

    Component Attributes

    Attributes on components are like instance variables in objects. They’re a way to save values that change, and a way to name those value placeholders.

    For example, let’s say we wanted to write a helloMessage component that prints a custom message. We can envision adding a message attribute to this component to customize its output.

    Example:

    <aura:component> 
        <aura:attribute name="message" type="String"/> 
        <p>Hello! [ message goes here, soon ]</p> 
    </aura:component>

    dont miss out iconCheck out another amazing blog here: Overview of Aura Components in Salesforce | The Developer Guide

    Expressions 

    An expression is basically a formula, or a calculation, which you place within expression delimiters (“ {!” and “ }”). 

    {!<expression>

    An expression is any set of literal values, variables, sub-expressions, or operators that can be resolved to a single value. 

    <aura:component> 
        <aura:attribute name="message" type="String"/> 
        <p>{!'Hello! ' + v.message}</p> 
    </aura:component>
  • Aura Component Framework and Attributes | All You Need to Know

    Aura Component Framework and Attributes | All You Need to Know

    What is the Lightning Component?

    A UI framework called component framework is used to create single page applications for desktop and mobile platforms. On the client side, JavaScript is used, and on the server, Apex. Compared to many other frameworks, the Lightning Component Framework makes it much simpler to design programs that function on both mobile and desktop devices. 

    Lightning comes with the Lightning Component Framework and a number of innovative developer tools. Lightning makes it simpler to create applications that are responsive across all devices. 

    Both the Lightning Web Components paradigm and the classic Aura Components model can be used to create Lightning components. 

    Where we use lightning component in Salesforce org

    • Lightning app builder
    • Community builder
    • Lightning pages
    • Lightning experience record pages
    • Quick action

    dont miss out iconDon’t forget to check out: Use Aura Component in Screen Flow | Salesforce Flow Builder Tutorial

    What are the Lightning Component Attributes?

    Attribute in lightning component is like a variable and it stores the different type of value.

    Syntax:

    <aura:attribute name="Anyname" type ="string" description="some description"  default="some default string"/>

    A parameter of an attribute, the most important one, is its name and type, and another parameter where we can specify an attribute’s description is its description. The parameter description is not necessary. In a similar vein, we have a default parameter that provides an attribute with a default value. We have an access parameter that allows us to choose public, private, or global access for an attribute when setting its access. The attribute is open to the public by default. 

    We have a required parameter that we can set to true or false to make an attribute compulsory. 

    • Boolean

    Syntax: 

    <aura:attribute name="xyz" type="Boolean" />

    We use the Boolean attribute when we want to store boolean values. 

    • Integer 

    Syntax: 

    <aura:attribute name="xyz" type="Integer" />

    We use integer attribute when we want to store integer value. 

    • String

    Syntax: 

    <aura:attribute name="xyz" type="String" />

    We use string attribute when we want to store string value.

    dont miss out iconCheck out another amazing blog by Narendra Kumar here: What are Decorators in a Lightning Web Component?

    • Date

    Syntax: 

    <aura:attribute name="xyz" type="Date" />

    We use date attribute when we want to store date value.

    • DateTime

    Syntax: 

    <aura:attribute name="xyz" type="DateTime" />

    We use datetime attribute when we want to store datetime value.

    • Double 

    Syntax: 

    <aura:attribute name="xyz" type="Double" />

    We use double attribute when we want to store double value.

    • Decimal

    Syntax: 

    <aura:attribute name="xyz" type="Decimal" />

    Decimal is better than Double for maintaining precision for floating-point calculations. It’s preferable for currency fields. 

    • Long

    Syntax: 

    <aura:attribute name="xyz" type="Long" />

    Long values can contain numbers with no fractional portion. Use this data type when you need a range of values wider than those provided by Integer. 

  • Introduction to Aura Components in Salesforce – Learn Here

    Introduction to Aura Components in Salesforce – Learn Here

    In this blog, we are going to study the topic of Aura Components in Salesforce. 

    Let’s begin with the Aura Components programming model: 

    • provides out-of-the-box components 
    • Event-Driven Architecture 
    • Framework optimized for performance 
    • Rich Component Ecosystem 
    • Fast Development 
    • Device aware and Cross Browser Compatibility 

    Aura Components are self-contained and reusable units of the app. Its framework includes a set of prebuilt components. We can combine and configure components to form new components in-app. A component can contain other components, as well as HTML, CSS, JS or any other web-enabled code. 

    Aura Component Bundle

    Component – The only required resource in a bundle. Contains markup for the component or app. Each bundle contains only one component or app resource. 

    CSS Styles – Styles for the component. 

    Controller – Client-side controller methods to handle events in the component. 

    Design – Required for components used in the lightning app builder or lightning pages. 

    Helper – JavaScript functions can be called from any JavaScript code in a component’s bundle. 

    Documentation – A description, sample code, and one or multiple references to example components. 

    Renderer – Client-side renderer to override default rendering for a component. 

    SVG – Custom icon resources for components used in the lightning App builder. 

    dont miss out iconDon’t forget to check out: Use Aura Component in Screen Flow | Salesforce Flow Builder Tutorial

    Four Language Framework

    • XML (XML Component Definition) 
    • CSS (Styling Components) 
    • JS (JS Controller, Helper and Renderer) 
    • Apex (Apex Controller) 

    What is a Component?

    A Component is a bundle that includes a definition resource written in markup and may include additional, optional resources like a controller, stylesheet and so on. 

    Syntax: 

    <aura:component > 
    <p> My First Lightning Aura Component </p> 
    </aura:component> 

    What is an Application?

    • An application is just a special kind of Component. 
    • You can think of an app as being different from a component in only two meaningful ways: 
    1. An App uses <aura:application> tag instead of <aura:component> tag.
    2. Only an app has a preview button in the Developer Console.

    Syntax: 

    <aura:application extends = "force:slds"> 
    <c:DemoComponent/> 
    </aura:application>

    Data Binding between Components

    • We can add a component in the markup of another component (also known as a container component). 
    • We can use an expression to initialize attribute values in the component based on the attribute values of the container component. 
    • There are two forms of expression syntax, which exhibit different behaviour for data binding between the components. 

    Two Ways of Data Binding

    • Unbounded Expressions 

                    Syntax 

                               {#expression} 

    • Bounded Expressions 

                    Syntax 

                              {!expression} 

    Unbounded Expression Example

    <!--c:parent--> 
    <aura:component> 
    <aura:attribute name=”parentAttr” type=”String” 
    default=”parent attribute”/> 
    <c:child childAttr =”{#v.parentAttr}”/> 
    </aura:component/> 

    Explanation 

    • {#v.parentAttr} is an unbounded expression. 
    • Any change to the value of the childAttr attribute in c:child does not affect the parentAttr attribute in c:parent and vice versa. 

    dont miss out iconCheck out another amazing blog by Bhawana here: Organization Wide Default (OWD) Sharing Settings in Salesforce

    Bounded Expression Example 

    <!--c:parent--> 
    <aura:component> 
    <aura:attribute name=”parentAttr” type=”String” 
    default=” parent attribute”/> 
    <c:child childAttr = “{!v.parentAttr}”/> 
    </aura:component/>

    Explanation 

    • {!v.parentAttr} is a bounded expression. 
    • Any change to the value of the childAttr attribute in c:child affects the parentAttr attribute in c:parent and vice versa. 
  • Salesforce Lightning Component Inside Lightning Web Component Using Visualforce Page

    Salesforce Lightning Component Inside Lightning Web Component Using Visualforce Page

    Why we need this feature:

    In our business, If we want to invoke a lightning web component on a visualforce page that has a parameter according to lightning component that is also combined in the same VF or its vice versa then this article will guide you to pass variables in bi-directional ways from LWC to LC or LC to LWC. In this article, we’re just using a constructor/connectCallback/initialization method to pass variables.

    1. Lightning web component:-  In our lightning web component we’re using CustomEvent that will fire in JS Controller connectedCallback and listen in VisualForce Page using document.addEventListener(“uploadevent”, function(event){}. We’re using the ‘@api’ decorator variable to get value from the lightning component.

    message='This is LWC for visualforce page';
        @api messageFromLc;   
        connectedCallback(){
            var selectedEvent = new CustomEvent('uploadevent', { detail:  {msg :this.message},
            bubbles: true,
            composed: false,
        });
        console.log('message in lwc'+this.message);
        // Dispatches the event.
        this.dispatchEvent(selectedEvent)
    }
    

    For more information about bubbles and composed 

    dont miss out iconDon’t forget to check out: Salesforce Lightning Aura Components Core Concepts

    2. Lightning Component:- In our lightning component we’re using aura:registerEvent tag to register our event that will fire after the JS Controller doInit method invoked and listen in VisualForce Page using $A.eventService.addHandler. We’re using the aura attribute variable with access public to get value from the lightning web component.

    lcCommunicateWithLWC
    Cmp File
     <aura:attribute name="currentUserName" type="string" />
        <aura:attribute access="public" name="messageFromLWC" type="string" />
        <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
        <aura:registerEvent name="vfEvent" type="c:sendDataLCtoVF"/>
    JS Controller
    fireEvent : function(component, event, helper) {
        var myEvent = $A.get("e.c:sendDataLCtoVF");
        myEvent.setParams({
            currentUserId: component.get('v.currentUserName')
        });
        myEvent.fire();
    },doInit: function(component,event,helper){
        component.set("v.currentUserName",$A.get("$SObjectType.CurrentUser.Id")); 
        var action = component.get('c.fireEvent');
        $A.enqueueAction(action);
    }
    

    3. Aura Application:- As we’re using VF Page to embed our Lightning Component inside Lightning Web Component. We need an aura application that fulfills this requirement.

    LWCTOVF.app
    <aura:application extends="ltng:outApp" access="global">
        	<aura:dependency resource="c:displayMessageOnLC"/>
        <aura:dependency resource="c:lcCommunicateWithLWC"/>
    </aura:application>
    

    dont miss out iconCheck out another amazing blog by Prafull here: Drag and Drop Address Field on Google Map | Salesforce Help Guide

    4. VisualForce Page :- In VF Page we’re using <apex:includeLightning /> and $Lightning.use to embed both LC & LWC.

    • Firstly we’re invoking LC (But not displaying) that will pass the LC message to LWC using  $A.eventService.addHandler({})

      $Lightning.use("c:LWCTOVF", function() {
          $Lightning.createComponent("c:lcCommunicateWithLWC", {
      }, "TempLC", function(cmp) {
          $A.eventService.addHandler({
              "event": "c:sendDataLCtoVF", "handler": retriveEventData});
          });
      });

      Now, In retriveEventData we’re invoking our LWC once it gets a message from LC. We also need to run once that’s why displayLWC variable used.

      var displayLWC; function retriveEventData(event) {
          if(displayLWC !== event.getParam("currentUserId")){
              console.log(event.getParam("currentUserId")); 
              displayLWC=event.getParam("currentUserId");
              $Lightning.createComponent("c:displayMessageOnLC", {
                  "messageFromLc": event.getParam("currentUserId")
              },
              "LWC",
              function(cmp) {
              });
              var userId = event.getParam("currentUserId");
              event.setParam("currentUserId",'dsdsadsa');
              document.getElementsByClassName("Id")[0].innerHTML ='Login User ID: '+ userId; 
          }
      }
    • Once our LWC is called and displayed on UI our document.addEventListener is invoked and passes the LWC message to LC using event.detail.msg and then we’re displaying correct LC on UI by invoking checkLC method in JS.

      function checkLC(){
          $Lightning.createComponent("c:lcCommunicateWithLWC", {
              "messageFromLWC":document.getElementsByClassName("Message")[0].innerHTML
          },
          "LC",
          function(cmp) {
          });
          document.getElementById("VF").style.display='block';
          document.getElementById("loadingLogo").style.display='none';
      }
  • An Introduction to Lightning Web Components | Salesforce Lightning

    An Introduction to Lightning Web Components | Salesforce Lightning

    Lightning web components are custom HTML components fabricated using HTML and standard JavaScript. Lightning web components and Aura components can coexist and interoperate on a page.  For both administrators & users, it shows up as components. In this top blog on salesforce, we will talk in detail about the Lighting web components and discuss in detail how it works.

    Lightning Web Components is built on top of standard Web Components technologies and provides only what is necessary to perform well in browsers supported by Salesforce. Because it runs natively in browsers, Lightning Web Components is lightweight and delivers exceptional performance. Much of the code you write is standard JavaScript and HTML.

    It is open source, that engages you to examine the source code, modify the behavior for your requirements, and gather enterprise-ready web components on any platform, not just Salesforce. 

    Previously, we required different frameworks to manufacture different sides of an application that encouraged external Salesforce. For example, we used the Aura component to develop the employee-defying side of an application on Salesforce. And also we used React, Angular, or Vue to build the customer-defying side of the application, and passed it on to Heroku or on another platform. Today, we can use Lightning web components to fabricate both sides of the application. The advantages of it are huge and with assistance from Top Salesforce Consultants, you would now be able to learn the framework at ease.

    We can simply create lightning web components using HTML, javascript, and CSS. 

    Benefits of Lightning Web Components

    • It gives an easy way to develop large-scale modular apps 
    • Also, we got the leverage of the latest web functionalities and constructs 
    • A web developer who is working on modern JS frameworks could easily ramp-up LWC 
    • Interoperable components 
    • Allow better performance

    With the right assistance from Salesforce Consulting Companies, you can take the leverage of lightning web components at ease

    These are the Fundamentals Pieces of your Component

    • HTML gives the structure to your component.
    • JavaScript describes the centre’s business logic and handles events.
    • CSS gives the look, feel, and animation to your component.

    dont miss out iconDon’t forget to check out: How to Convert sforce.apex.execute to Lightning | Salesforce Developer Guide

    Let’s take a simple example of the Lightning web component:

    HTML:

    <template>
        <input value={message}></input>
    </template>
    

    JavaScript:

    import { LightningElement } from 'lwc';
    export default class App extends LightningElement {
        message = 'Hello World';
    }
    
    

    CSS:

    input {
        color: red;
    }

    Decorators in Lightning Web Component

    LWC has three decorators that append functionality to property or function. The capability to create decorators is part of ECMAScript and these three decorators are unique to LWC.

    • @api: It is used to expose public property. And the public property is reactive & if you want to change the reactive property value, the component is re-rendered. So you know that when a component is rerendered, all the expressions used in the template are reconsidered once again. @api passes the public property values from the parent component.
      If you want to use @api decorators, you have to import it explicitly from lwc.
      Import { LightningElement, api } from ‘lwc’;
    • @track: If you want to track private reactive property value  & also rerender a component when it changes, decorate it with @track. We can use the private property only in the component where it is defined.
      If you want to use @api decorators, you have to import it explicitly from lwc.
      Import { LightningElement, track } from ‘lwc’; 
    • @wire: It is used to read the Salesforce data. LWC uses a reactive wire service. @wire is used to call apex method in lwc js controller.
      If you want to use @api decorators, you have to import it explicitly from lwc.
      Import { LightningElement, wire } from ‘lwc’;

    dont miss out iconCheck out another amazing blog by Shweta here: Stages of Salesforce CPQ Implementation

    And also you have to import wire Syntax as shown below:

    Import apexMethodName from ‘@salesforce/apex/Namespace.Classname.apexMethodReference’;

    1. apexMethodName: It recognizes the apex method.
    2. apexMethodReference: Imported Apex method name.
    3. Classname: Apex class name.
    4. Namespace: You know that the default namespace of the Salesforce org is ‘c’, in this case, don’t specify a namespace. The namespace is used when your apex class is in a managed package.

    Important point: For property, we can have only one decorator at a time.

  • Application Event in Lightning Component in Salesforce

    Application Event in Lightning Component in Salesforce

    As we have discussed Component Events in my previous blog which is also one of the events helps to communicate between two components.

    Now you might be thinking when there are Component Events why we should use Application Events, well there is a difference between these two custom events.

    First of all, let us know the differences i.e. Component Events can be handled by the same component or a component that contains the component or a component that instantiates while Application Events are handled by any component defined for the event.

    One of the best things this Application Component can have is it can be used throughout the application.

    Attribute tag used for Application Component is as follows:

    type=’’Application’’ in the aura:event tag

    During the handling of application events, there is no need to specify name attribute in aura:handler.

    To get an instance of Application type event, we use,

    $A.get(“e.myNamespace:myAppEvent’’) in javascript.

    dont miss out iconDon’t forget to check out: Sort Picklist Values in Lightning Component | Salesforce Tutorials

    Let’s take an example of Application Event:

    1. Firstly create an application event named ExampleApplicationEvent which is used to pass the values from ParentApplicationEvent to ChildApplicationEvent.

    You have to give type as Application in order to use the Application Event.

    <!--ExampleApplicationEvent.evt-->
    <aura:event type="APPLICATION" description="Example of Application Event" >
        <aura:attribute name="Text" type="string" />
    </aura:event>
    1. Secondly, create a ParentApplicationEvent Component which is used to register the application event and we made a button on click of that, we can get the parameter which we set using JS Controller.

    We have to use aura register event to use application/component events and the name must be the same as given in the event.

    <!--ParentApplicationEvent-->
    <aura:component >
        <aura:registerEvent name="ExampleApplicationEvent" type="c:ExampleApplicationEvent"/>
        <lightning:button label="Tap to fire the event" variant="brand" onclick="{!c.ParentComponentEvent}"/>
    </aura:component>
    1. Thirdly we create a ParentApplicationEvent JS Controller which is used to get an event using the event name and set the parameter.

    Here we used setParams, you can also use setParam they are both the same thing.

    ({
        ParentComponentEvent : function(component, event, helper) {
            //You can get the event using event name
            var ExAppEvent = $A.get("e.c:ExampleApplicationEvent");
            // Set here event attribute value
            ExAppEvent.setParams({"Text" : "Welcome To"});
            ExAppEvent.fire();
        }
    })
    1. Fourthly we create a ChildApplicationEvent Component which is used to handle the component which is fired using the handler.
    <!--ChildApplicationEvent-->
    <aura:component >
        <aura:attribute name="eventText" type="String"/>
        <aura:handler event="c:ExampleApplicationEvent" action="{!c.ChildComponentEvent}"/>
        <div class="slds-m-around_xx-medium">
            <p>{!v.eventText}</p>
        </div>
    </aura:component>
    1. Fifthly we create a ChildApplicationEvent JS Controller.
    ({
        ChildComponentEvent : function(component, event, helper) {
            //You can get the event text attribute here
            var text = event.getParam("Text");
            // Set here event attribute handler values
            component.set("v.eventText", text + ' World! ');
        }
    })

    dont miss out iconCheck out another amazing blog by Deepak here: Objects Related To Salesforce Files And Connection Between Them

    1. At last, we have created a Lightning Application which is used to preview the component.
    <aura:application extends="force:slds">
        <c:ParentApplicatioEvent/>
        <c:ChildApplicationEvent/>
    </aura:application>

    I have explained stepwise how to use Application Events in Lightning Components. If you still have doubt feel free to ask.

    Happy Coding!

    Reference: biswajeetsamal

  • Introduction of Leaflet Map in Salesforce Lightning Component

    Introduction of Leaflet Map in Salesforce Lightning Component

    The Leaflet is an open-source JavaScript library that is used for mobile-friendly interactive maps. It has all the mapping features. It works very well across all media screens. The performance and design of the leaflet are very standard. It can be extended by lots of plugins and it has also a beautiful, well-documented API that helps developers to design a specific map.

    Don’t forget to check out: How to use Leaflet Map in Salesforce?

    If we are talking about the use of leaflet maps in the Salesforce lightning component. We can easily use it by importing Leaflet as a static resource in our Salesforce Org.

    Add static resource using steps: Setup -> Build -> Develop -> Static Resources -> New. Write the name and choose the downloaded zip file from the above link and save.

    Let’s take a tour to show the leaflet map in our Salesforce lightning component:

    Create a new lightning component named as ‘leafletComponent’.

    Component:

    <aura:component>
        <aura:attribute name="map" type="Object"/>
        <ltng:require styles="/resource/leaflet/leaflet.css" scripts="/resource/leaflet/leaflet.js" afterScriptsLoaded="{!c.jsLoaded}" />
        <div id="map"></div>
    </aura:component>

    JScontroller:

    ({
        jsLoaded : function(component, event, helper) {
            var map = L.map('map', {zoomControl: false}).setView([37.784173, -122.401557], 2);
            L.tileLayer(
                'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}',{
                    attribution: 'Tiles © Esri'
                 }).addTo(map);
            component.set("v.map", map);
        }
    })

    Style:

    .THIS {
        width: 100%; 
        height: 50%;
    }

    Create a Lightning App to preview above component:

    <aura:application>
        <c:leafletComponent/>
    </aura:application>

    Following is the view of the leaflet map :

    Salesforce Leaflet-0

    How to add the marker on leaflet map:

    Component: Same as above

    JScontroller:

    ({
        jsLoaded : function(component, event, helper) {
            var map = L.map('map', {zoomControl: false}).setView([51.5, -0.09], 2);
            L.tileLayer(
                'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', {
                    attribution: 'Tiles © Esri'
                }).addTo(map);
            component.set("v.map", map); 
            L.marker([51.5, -0.09]).addTo(map).bindPopup('A custom marker').openPopup(); 
        }
    })

    Style: Same as Above.

    How to add Circle and Polygon on Map:

    Component: Same as above

    JScontroller:

    ({
        jsLoaded: function(component, event, helper) {
            var map = L.map('map', {zoomControl: false}).setView([51.5, -0.09], 13);
            L.tileLayer(
                'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', {
                    attribution: 'Tiles © Esri'
                }).addTo(map);
            component.set("v.map", map);
            var circle = L.circle([51.508, -0.11], {
                color: 'red',
                fillColor: '#f03',
                fillOpacity: 0.5,
                radius: 500
            }).addTo(map);
            var polygon = L.polygon([
                [51.509, -0.08],
                [51.503, -0.06],
                [51.51, -0.047]
            ]).addTo(map);
        }
    })

    Style: Same as Above.

    Following is the view of Marker, Circle, and Polygon on leaflet map:

    Leaflet-1

    How to play with events:

    Every time something happens in Leaflet, e.g. user clicks on a marker or map zoom changes, the corresponding object sends an event that you can subscribe to with a function. The following code shows the latitude and longitude of the place where the user clicked on the map.

    Component: Same as above.

    JScontroller:

    ({
        jsLoaded: function(component, event, helper) {
            var map = L.map('map', {zoomControl: false}).setView([51.5, -0.09], 13);
            L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', {
                attribution: 'Tiles © Esri'
                }).addTo(map);
            component.set("v.map", map);
    
            var popup = L.popup();
            function onMapClick(e) {
                popup
                .setLatLng(e.latlng)
                .setContent("User clicked the map at " + e.latlng.toString())
                .openOn(map);
            }
            map.on('click', onMapClick);
        }
    })

    Style: Same as Above.

    Following is the view of showing dynamic latitude and longitude using the event on leaflet map:

    Leaflet-2

    There are a lot of plugins of leaflet map which is used to show different functionalities.