In Lightning, we should always be using e.force:navigateToSObject
or e.force:navigateToURL
instead of links like <a href="whatever>
. So, I made a custom Link component to avoid having to have Javascript controllers all over the place just to handle links:
Component:
<aura:component access="global">
<aura:attribute name="type" type="String" default="a" />
<aura:attribute name="class" type="String" />
<aura:attribute name="recordId" type="String" />
<aura:attribute name="relativeUrl" type="String" />
<aura:attribute name="id" type="String" />
<aura:if isTrue="{!v.type == 'button'}">
<button id="{!v.id}" class="{!v.class}" onclick="{!c.onClick}">
{!v.body}
</button>
<aura:set attribute="else">
<a id="{!v.id}" class="{!v.class}" onclick="{!c.onClick}">
{!v.body}
</a>
</aura:set>
</aura:if>
</aura:component>
Controller:
({
onClick : function(component, event, helper) {
var recordId = component.get('v.recordId');
var navEvt;
if(recordId) {
navEvt = $A.get("e.force:navigateToSObject");
navEvt.setParam("recordId", recordId);
} else {
navEvt = $A.get("e.force:navigateToURL");
navEvt.setParam("url", component.get('v.relativeUrl'));
}
navEvt.fire();
}
})
This is all great on Desktop, but the links don't work on Safari/iOS. The button version does, but not the <a>
version.
Now, the Lightning docs say that the framework handles turning an onclick into a touch event:
Don’t Use onclick and ontouchend Events
You can’t use different actions for onclick and ontouchend events in a component. The framework translates touch-tap events into clicks and activates any onclick handlers that are present.
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/events_anti_patterns.htm
So, this implies that I shouldn't need to add a ontouchend event to my <a>
tag, but doing so does make my links work on iPad. Is this a bug in the framework? Am I being stupid about how to use <a>
tags in Lightning? Unfortunately, googling about anything related to <a>
is never very helpful.