Note: This release is in preview. Features described here don’t become generally available until the latest general availability date that Salesforce announces for this release. Before then, and where features are noted as beta, pilot, or developer preview, we can’t guarantee general availability within any particular time frame or at all. Make your purchase decisions only on the basis of generally available products and features.

Best Practices for Conditional Markup

Using the <aura:if> tag is the preferred approach to conditionally display markup but there are alternatives. Consider the performance cost and code maintainability when you design components. The best design choice depends on your use case.

Conditionally Create Elements with <aura:if>

Let’s look at a simple example that shows an error message when an error occurs.

1<aura:if isTrue="{!v.isError}">
2    <div>{!v.errorMessage}</div>
3</aura:if>

The <div> component and its contents are only created and rendered if the value of the isTrue expression evaluates to true. If the value of the isTrue expression changes and evaluates to false, all the components inside the <aura:if> tag are destroyed. The components are created again if the isTrue expression changes again and evaluates to true.

The general guideline is to use <aura:if> because it helps your components load faster initially by deferring the creation and rendering of the enclosed element tree until the condition is fulfilled.

Toggle Visibility Using CSS

You can use CSS to toggle visibility of markup by calling $A.util.toggleClass(cmp, 'class') in JavaScript code.

Elements in markup are created and rendered up front, but they’re hidden. For an example, see Dynamically Showing or Hiding Markup.

The conditional markup is created and rendered even if it’s not used, so <aura:if> is preferred.

Dynamically Create Components in JavaScript

You can dynamically create components in JavaScript code. However, writing code is usually harder to maintain and debug than using markup. Again, using <aura:if> is preferred but the best design choice depends on your use case.