3

I need to generate a page URL and use it a link to my page. Users can click on that link and go to the page.

controller

getPageUrl: function (component) {
        const navService = component.find("navService");
        const pageReference = {
            type: 'comm__namedPage',
            attributes: {
                pageName: "my-page",
                actionName: "view"
            }
        };
        const defaultUrl = "#";
        navService.generateUrl(pageReference)
            .then($A.getCallback(function (url) {
                component.set("v.myPageUrl", url ? url : defaultUrl);
            }), $A.getCallback(function (error) {
                component.set("v.myPageUrl", defaultUrl);
            }));
    }

component

<aura:component>
   <aura:attribute name="myPageUrl" type="String" access="private"/>
   <aura:handler name="init" value="{! this }" action="{! c.getPageUrl }" />
   <p>Go to <a href="{! v.myPageUrl }">my page</a>.

</aura:component>

What bothers me is that the name of the page is hardcoded - pageName: "my-page". Is there a better way or best practice of how to avoid hardcoding in this case?

4

You can use an auraAttrubute to store the page you want to use.

<aura:attribute name="pageName" type="String"/>

How can you choose the page to use?

Sorry, but i don't have enough reputation to comment your post, so i used this way :D

New contributor
Christian Croce is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
  • Yes, it might bring in some convenience, yet in this case it still would be hardcoded in the attribute value. What if the page name changes, then you will have to update your lightning component anyways. I am considering storing page names in settings (custom or metadata type), but I am not sure it's worth all the fuss. – Eduard Nov 8 at 12:11
  • Like i said, it depends of the component usage. if you want to use it as a child component, you can made the attribute public or global – Christian Croce Nov 8 at 13:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.