I have a html string embedded in a map function like this

    pnp.sp.web.lists.getByTitle("Division").items.select("Title","ID").get().then((item: any[]) =>  divtree=item.map(per =>'<li id='+per.Title+' style="cursor:pointer" onclick="myfunction()" >'+per.Title+'</li>');
    divtree.toString().replace(/,/g , "");});
    divtree: divtree

This is used in return like this

   <div dangerouslySetInnerHTML={{__html: this.state.divtree}} ></div>

I m declaring the function myfunction() like this

    private myfunction(): void { console.log('working') }

My problem is that when I click on the li element which was created dynamically I get the error myfunction() function is not defined

1 Answer 1


The simplest option here is declare the function not as a class member but just like a variable in window like

window.myFunction = function {}

But I would look at removing your dangerous html insertion at all. You can return a set of React components from your .map function and insert them into div. Like that

var els = items.map(i => return (<li>...</li>););
And then

In that case you’ll be able to use React syntax to add even handler:

<li onClick={this.myFunction.bind(this)}>
  • it worked with window.myfunction but with a difference like (window as any).myfunc=function(){} due to tsx Jan 18, 2018 at 5:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.