0
votes

I'm trying to add a click eventlistener on each item from a SharePoint list in an SPFx webpart using React

The webpart html generated looks like below:

<div class="visualstyle_276d6985">
<h1>Active People</h1>
<ul class="peoplelist_276d6985">
<li class="activeperson" id="id3">Alistair Speirs</li>
<li class="activeperson" id="id22">Obeida Bakhach</li>
</ul>
</div>

In the webpart render method, I call

ReactDom.render(element, this.domElement);

Then I try to add the addEventListeners

My problem is that I only get 1 element returned

public render(): void {
const element: React.ReactElement<ICandidateListWebPartProps > =    React.createElement(
ActivePersonList,
{
description: this.properties.description,
siteurl: this.context.pageContext.web.absoluteUrl,
activepersonList: null
}
);

ReactDom.render(element, this.domElement);
this.setOnClickHandlers();
}

private setOnClickHandlers() : void {
const webPart: ActivePersonListWebPart = this;
let listItems = this.domElement.querySelectorAll("li.activeperson")
let itemCt:number = listItems.length;
//change to .Foreach once this works
for(let j:number = 0; j<itemCt; j++){
listItems[j].addEventListener('click', (event) => {
this.liClicked(event.target);
});
}
}

private liClicked(target): void{
let me:any = target;
alert(target);
}

When I call

this.domElement.querySelectorAll("li.activeperson")

I get the first li element, not all (or both in my example)

I would expect that I could get all of them.

1

1 Answers

0
votes

I think that I figured this out.
I want to use the querySelectorAll against the tag.

Then on the function access the event.target

private setOnClickHandlers(webPart) : void {
  let listItems = this.domElement.querySelectorAll("ul")
  for(let j:number = 0; j<listItems.length; j++){
    listItems[j].addEventListener('click', (event) => {
      this.liClicked(event);
    });
  }
}

private liClicked(ev): void{
  let me:any = ev.target;
  alert(me.id);
}