How to get URL parameters in LWC?
Hello Folks,
Today I wanna show you how to get URL parameters in the LWC component using CurrentPageReference.
Letβs get started.
Introduction
The easiest way to get url params will be to use CurrentPageReference.
- currentPageReference.state β contains the key β value pairs of URL query parameters.
- currentPageReference.state.parameterName β allows to get specific param from URL.
// currentPageReference { attributes: { name: URL_Test_Page__c }, state: { lang: en_US, type: test-type, id: 000000000001 }, type: comm__namedPage }
As you can see in the code above β currentPageReference includes page API Name and type.
Reference page types that are supported:
- App β standard__app
- Lightning Component β standard__component
- Knowledge Article β standard__knowledgeArticlePage
- Login Page β comm__loginPage
- Named Page (Communities) β comm__namedPage
- Named Page (Standard) β standard__namedPage
- Navigation Item Page β standard__navItemPage
- Object Page β standard__objectPage
- Record Page β standard__recordPage
- Record Relationship Page β standard__recordRelationshipPage
- Web Page β standard__webPage
Assumptions
- Since the key-value pairs of
PageReference.state
are serialized to URL query parameters, all the values must be strings. - @wire service getStateParameters will be fire automatically every time URL params will change.
Code
import { LightningElement, wire } from 'lwc'; import { CurrentPageReference } from 'lightning/navigation'; export default class MyComponentName extends LightningElement { urlId = null; urlLanguage = null; urlType = null; @wire(CurrentPageReference) getStateParameters(currentPageReference) { if (currentPageReference) { this.urlId = currentPageReference.state?.id; this.urlLanguage = currentPageReference.state?.lang; this.urlType = currentPageReference.state?.type; } } }
Repository
If you have some questions feel free to ask in the comment section below. π
Was it helpful? Check out our other great posts here.