2

How do I migrate a

<div aura:id="foo"></div

from Aura to LWC when I use Aura Id for finding?

cmp.find("foo");
4

I have found the LWC docs to offload some of this to the MDN docs, so bringing this one layer higher (in the actual LWC docs would be nice) would have made it easier for us.

In scenarios where there are two components of the same type on your template, the equivalent to aura:id is to use a data-id tag and select it like this:

this.template.querySelector('[data-id="userform"]')

4

The equivalent of using aura:id and component.find() in LWC is to use a standard DOM query selector like this:

const element = this.template.querySelector('selector');
element.doSomething();

We do have a restrictions to that standard behavior: you cannot use the id attribute as a selector as these are autogenerated by the framework. You are free to use any tag name or CSS class to filter the element that you wish to retrieve.

See Documentation.

  • 1
    Adding to this, if you want 1:1 equivalency, you can use this.template.querySelector('[data-id="userform"]'). This helps if there are multiple of the same component. – tsalb Feb 18 at 18:28
  • Thats worth its own answer. – Robert Sösemann Feb 18 at 22:05
  • Using a custom attribute will work but it has a performance impact. CSS attribute selectors don't perform that well so you may be better off by adding a class attribute (even if you don't use it for styling) and use it to discriminate the right component: this.template.querySelector('.unique-class-name') – POZ Feb 20 at 13:54

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.