+ Start a Discussion
Ankur SrivastavaAnkur Srivastava 

Conditionally render lightning app/component in VF page.

How can I conditionally render a lightning component/app in my VF page based on a button click ? I have a lightning lookup component which I want to render when I click a search button on my VF page.
Best Answer chosen by Ankur Srivastava
Mohith Kumar ShrivastavaMohith Kumar Shrivastava
Ankur,

Only onclick of button you will call the function that renders your lightning component .The JS code just draws the lightning component to the DOM and its not necessary to call the function on Onload ,instead you can call the function onclick of button 
 
<script>
function injectComponent(){
   

             		$Lightning.use("c:SalesLeaderBoardVfApp", function() {
	                 	$Lightning.createComponent("c:SalesLeaderMain", {},
	                     "leaderboard",
	                     	function(cmp) {
	                         // do some stuff
	                     	});

             		});

}

</script>

<button onclick="injectComponent()" lable="submit"/>

 

All Answers

Yury BondarauYury Bondarau

Ankur,

 

You can use the following components on a visualforce page

<apex:outputPanel id="lightning_container" rendered="{!isLightningActivated}">
in conjunction with
<apex:commandButton rerender='lightning_container' action='{!activateLightning}'>
In page controller you need to set isLightningActivated flag when button clicks, for instance:
public Boolean isLightningActivated{get;private set;}

public void activateLightning () {
    this.isLightningActivated = TRUE;

}

See more details here: https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_compref_outputPanel.htm

Ankur SrivastavaAnkur Srivastava
Hi Yury, Thanks for your reply. But the catch is that a lightning component/App is added in the VF page through a javascript function. (Refer: https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/components_visualforce.htm). And I don't know how to render a Javascript code conditionally on click of my search button.
Mohith Kumar ShrivastavaMohith Kumar Shrivastava
Ankur,

Only onclick of button you will call the function that renders your lightning component .The JS code just draws the lightning component to the DOM and its not necessary to call the function on Onload ,instead you can call the function onclick of button 
 
<script>
function injectComponent(){
   

             		$Lightning.use("c:SalesLeaderBoardVfApp", function() {
	                 	$Lightning.createComponent("c:SalesLeaderMain", {},
	                     "leaderboard",
	                     	function(cmp) {
	                         // do some stuff
	                     	});

             		});

}

</script>

<button onclick="injectComponent()" lable="submit"/>

 
This was selected as the best answer