How to use Aura Component in Visualforce Page?

How to use Aura Component in Visualforce Page?

Use Lightning Components in Visualforce Pages

ยท

4 min read

In this article, we will discuss how to show Aura Component on Visualforce Page. We will fetch account records using the apex controller in an Aura Component and embed that aura component in the Visualforce page. Follow below mentioned steps to do that.

Create an Apex Controller

We will create an Apex class Named AccountsController which contains a method named getAccounts. As the class needs to be accessed from Aura Component that is why we will use AuraEnabled annotation.

public class AccountsController {
@AuraEnabled
    public static List<Account> getAccounts()
    {
        List<Account> accList = [Select Name,Phone,Industry from Account limit 50];
        if(accList.size()>0)
        {
            return accList;
        }
        return null;
    }
}

Create Aura Component

We will create an AuraComponent named AccComponent and will use the controller created in the last step to fetch accounts from Salesforce.

We have used table tags to show the list of accounts and also used SLDS for styling purposes.

<aura:component controller="AccountsController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
     <aura:attribute name="accounts" type="Account[]"/>
     <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>



    <lightning:layout>
        <lightning:layoutItem padding="around-small" size="12">
            <div class="slds">

                <table class="slds-table slds-table--bordered slds-table--striped">
                    <thead>
                        <tr>
                            <th scope="col"><span class="slds-truncate">Name</span></th>
                            <th scope="col"><span class="slds-truncate">Phone</span></th>
                             <th scope="col"><span class="slds-truncate">Industry</span></th>
                        </tr>
                    </thead>
                    <tbody>
                        <aura:iteration items="{!v.accounts}" var="res">
                            <tr >
                                <td scope="row">
                                    <div class="slds-truncate" title="{!res.Name}">
                                        {!res.Name}
                                    </div>
                                </td>
                                <td scope="row">
                                    <div class="slds-truncate" title="{!res.Phone}">
                                        {!res.Phone}
                                    </div></td>
                                <td scope="row">
                                    <div class="slds-truncate" title="{!res.Industry}">
                                       {!res.Industry}
                                    </div>
                                </td>

                            </tr>
                        </aura:iteration>
                    </tbody>
                </table>
            </div>
        </lightning:layoutItem>
    </lightning:layout>
</aura:component>

To load the list of Accounts in the table we need to connect the Aura component to Apex Controller. We will access the getAccounts method from Aura Component's controller.

Below is the code you have to write to connect Aura with Apex but don't forget to use the controller attribute in the Aura component and pass the name of the correct apex class.

({
     doInit : function(component, event, helper) {
        let action = component.get("c.getAccounts");
        action.setCallback(this, function(response)
                           {
                               let state = response.getState();
                               if(state=='SUCCESS')
                               {
                                   component.set("v.accounts",response.getReturnValue());
                               }
                               else
                               {
                                   console.log('Failed to Retrieve To Accounts');
                               }
                           });
        $A.enqueueAction(action);
    }
})

Create Lightning Application

To display our Aura Component on the Visualforce page we have to create a Lightning Application. Also, we need to include <aura: dependency> tag which indicates that it uses a custom lightning component. Under the <aura: dependency> tag we need to mention our Lightning component.

We have created a lightning application named AccountApp. Below is the code of the lightning application which consists of <aura: dependency> tag.

<aura:application access="GLOBAL"  extends="ltng:outApp" implements="ltng:allowGuestAccess">
    <aura:dependency resource="c:AccComponent"/>
</aura:application>

Create Visualforce Page

As our primary objective was to show Aura Component on the Visualforce page so let's create a Visualforce page name AccountPage.

  • Add <apex:includeLightning/> at the beginning of your page. This component loads the JavaScript file used by Lightning Components for Visualforce.

  • $Lightning.use() method is used to refer to the Lightning application in which we need to add our Lightning application name.

  • $Lightning.createComponent is used to create a Lightning component dynamically in which we need to add our Lightning component name.

Below is the code of our Visualforce page which consists of <apex:includeLightning/> at the beginning of the page along with Lightning.use() & Lightning.createComponent.

<apex:page showHeader="false" standardStylesheets="false">
    <apex:includeLightning />

    <div id="datatable"></div>
    <script>
        $Lightning.use("c:AccountApp", function() {
            $Lightning.createComponent(
                "c:AccComponent",
                {},
                "datatable",
                function(cmp) {
                    console.log("Lightning Aura Component is Loaded...");
                }
            );
        });
    </script>
</apex:page>

Once you have created the Visualforce page click on the preview button and you will see the list of accounts visible on the Visualforce page.

Below is the output of the Visualforce page.

Conclusion

In short, you have to create an Aura Application which uses the <aura:dependency> tag, then on the Visualforce page we have to add <apex:includeLightning/> at the beginning of the page and we will use Lightning.use() to refer the application & Lightning.createComponent to create lightning component dynamically.

This way, you can use the Lightning component on the Visualforce page.

I hope you find this article helpful.

Please don't forget to like, comment and share and you can also check out my other articles. Also, don't forget to subscribe to my newsletter so you can be notified about new articles.

I am looking to get into technical writing so if you want me to write an article then please connect with me on my Twitter handle here.

Let me also know which topic I should write about next.

Did you find this article valuable?

Support shubham lashkan by becoming a sponsor. Any amount is appreciated!

ย