Using Lightning Components on a Visualforce Page

Lightning components can be used in visualforce pages using a lightning:app, which is otherwise just used to preview your lightning components only.

Steps to use Lightning Components on a Visualforce page

In we want to add/use a lightning component, we need to follow the following steps :

Create the Lightning App

1. Create a lightning:app with the “ltng:outApp” extension. This interface lets us use this app on a visualforce page. Go to the developer console -> File -> New -> Lightning Application and name the app as ‘LightningAppHost’. Paste the following code :

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

The aura:dependency tag defines what components we want this app to expose on the visualforce page. The resource attribute in the dependency can point to any standard (example, lighting:button) or custom lightning component. In this example, we have exposed a custom component called “MyFirstComponent” (which we created in an earlier example).

Create the Container Visualforce Page

2. Now, we need to create a visualforce page to display our lightning component. Go to Setup -> Visualforce Pages -> New (give it the name ‘LightningVF’) and paste the following code in your visualforce page :

    <apex:includeLightning />

The apex:includeLightning tag in the visualforce markup loads the javascript file required to run lightning components in your visualforce page.

Add Javascript to create your lightning component

3. Now, add the following code to your visualforce page :

    <apex:includeLightning />
    <div id="lightning" />
        $Lightning.use("c:LightningAppHost", function() {
              function(cmp) {
                 alert('Component Created');

We call the $Lightning.use method to use the app that we defined, the LightningAppHost app and then we call the $Lightning.createComponent to create the MyFirstComponent.

We need to assign it to an html element with the id, in this example we use the ‘lightning’ id which corresponds to the div element with the same id.

Then we can pass attributes in a json format, hence the empty json {}. We can pass the attribute values in this json format.

And lastly, we have a function which is called after the component has been created, we are doing an alert after the component has been created. This is the output after the component is loaded :

1. We see an alert with the message ‘Component Created’.

2. Then we see our lightning component loaded in the visualforce page in the salesforce classic UI.

Subscribe Now