2
  1. Can I invoke LWC component from a URL? or should I wrap the LWC Component in an aura component and then invoke the aura component?
  2. If I can invoke the LWC component directly from URL, how can I read any parameters in LWC Component that may have been passed at the time of invocation?

My requirement is simple:

  • I am displaying an URL- "Create New Type1 Lead" on home page which will not only invoke the "createLead" LWC component but also passes the recordTypeId for "Type1" lead.
  • I should be able to read the recordTypeId url parameter value inside LWC component and make decisions accordingly.

2 Answers 2

3

The best way to get parameters from URL is use CurrentPageRefference.

currentPageReference.state allows you to get params.

import { LightningElement, wire } from 'lwc';
import { CurrentPageReference } from 'lightning/navigation';

export default class Test extends LightningElement {

    currentPageReference = null; 
    urlStateParameters = null;

    urlId = null;
    urlLanguage = null;
    urlType = null;

    @wire(CurrentPageReference)
    getStateParameters(currentPageReference) {
       if (currentPageReference) {
          this.urlStateParameters = currentPageReference.state;
          this.setParametersBasedOnUrl();
       }
    }

    setParametersBasedOnUrl() {
       this.urlId = this.urlStateParameters.id || null;
       this.urlLanguage = this.urlStateParameters.lang || null;
       this.urlType = this.urlStateParameters.type || '10';
    }
}

More details you can find here https://salesforceprofs.com/how-to-get-url-params-in-lwc/

-1

parameters = {};

connectedCallback() {

    this.parameters = this.getQueryParameters();
    console.log(this.parameters);
}

getQueryParameters() {

    var params = {};
    var search = location.search.substring(1);

    if (search) {
        params = JSON.parse('{"' + search.replace(/&/g, '","').replace(/=/g, '":"') + '"}', (key, value) => {
            return key === "" ? value : decodeURIComponent(value)
        });
    }

    return params;
}
1
  • 1
    I've downvoted this because it's a code dump. The explanation as to how something works is as important as the solution itself. Without an explanation, it's hard for people to learn, adapt it to their own situation, or fix minor errors.
    – Derek F
    Commented Jul 28, 2021 at 14:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .