Hello Trailblazers!
In this post, we will learn how to use the lwc:ref
directives to query and reference the DOM elements from the Lwc Component.
This is a great alternative for the id
attribute which is not
recommended for use in the LWC Framework.
With the help of lwc:ref
you no longer need to use the
querySelector
which might be a little bit difficult to use.
If you are familiar with the Aura Component framework this is somewhat similar
to aura:id
and cmp.find("id")
from Aura
Component Framework.
How to use lwc:ref
First of all, you need to set lwc:ref
directive to the
element and set a value to it. This value is text in camel case format which
can be used to uniquely identify the DOM element.
Here are some examples of valid values for lwc:ref
directive:
myDiv
, myComponent
, box
, etc.
After that, you can access the element in the JS file using this syntax:
this.refs.<attribute-value>
. For example
this.refs.myDiv
.
With this reference, you can access all properties and functions of the referenced element.
The below example shows how we can reference elements, set attributes, or call public functions of the DOM elements.
myComponent.html
<template> <lightning-input lwc:ref="userName" type="text" label="User Name"> </lightning-input> <!-- use with native html --> <div lwc:ref="myDiv"></div> <!-- use with custom component --> <c-child lwc:ref="childCmp"></c-child> </template>
myComponent.js
export default class MyComponent extends LightningElement { renderedCallback() { // get userName console.log("userName ", this.refs.userName.value); // set value to the input. this.refs.userName.value = "default@username" // get the div console.log(this.refs.myDiv); // get the custom child component and call @api function this.refs.myDiv.publicFun(); } }
Important points to remember about lwc:refs
-
If you call
this.refs
for the component that does not exist, it returnsundefined
. -
When multiple components are assigned the same
lwc:ref
value then the last component in the DOM. -
Expressions are not supported for
lwc:ref
, only text is allowed. -
The value
this.refs.myCmp
is not accessible in connectedCallback as the components are not rendered yet. - Don't forget to add a null check for
this.refs
. - As of now, refs don't work with elements inside
for:each
No comments :
Post a Comment
Hi there, comments on this site are moderated, you might need to wait until your comment is published. Spam and promotions will be deleted. Sorry for the inconvenience but we have moderated the comments for the safety of this website users. If you have any concern, or if you are not able to comment for some reason, email us at rahul@forcetrails.com