How do you define an element with an ID attribute using LWC?

I’d like to be able to link to certain portions of my page using URL fragments, eg:

<h3 id="overview">Overview</h3>

...
<a href="#overview">Go to Overview</a>

Unfortunately the IDs i set from within LWC templates get overwritten, so my links don’t work. Is there any way to define the ID attribute so it won’t change?

Answer

Assuming you want to scroll to an element you have access to, you could always use scrollIntoView:

this.template.querySelector("h3").scrollIntoView();

You can basically use any valid CSS selector to find a specific element (e.g. based on a data-id or another attribute).

As far as I can tell, from a lack of documentation, you can’t specify an anchor target. You would write the link like this:

<a onclick={handleClick} data-target-id="overview">Overview</a>

Given an H3 like this:

<h3 data-id="overview">Overview</h3>

And scroll with this:

handleClick(event) {
  let targetId = event.target.dataset.targetId;
  let target = this.template.querySelector(`[data-id="${targetId}"]`);
  target.scrollIntoView();
}

((Note: Not tested, you might need to tweak the CSS selector.))

This assumes that the link and target are in the same template, otherwise this won’t work. As far as I can tell, you can’t target arbitrary elements.

Attribution
Source : Link , Question Author : Brendan Roy , Answer Author : sfdcfox

Leave a Comment