0

I have an HTML Div element (lets call it ELEM) .

ELEM has an "onclick" event handler which does something .

I also use SPFX to create a Webpart and use it on the same page as ELEM.

I want to set ELEM as the webpart's child.

And for that I use "dangerouslySetInnerHTML" .

The ELEM does appear as a child ,however the "onclick" handler stops working .

What am I missing?

edit: For plain react ie without spfx it works just fine see live https://codesandbox.io/p/sandbox/event-handler-inner-html-7m7gxz

1 Answer 1

0

If I understand correctly, you are copying an element residing outside of your SPFx webpart and then want it to appear inside your SPFx webpart.

This is a little unconventional, but if you need your ELEM to have a working onclick event, you need to register it.

Sample code:

const elemRef = useRef<HTMLDivElement>(null);

useEffect(() => {
if (elemRef.current) {
 
  elemRef.current.addEventListener('click', handleClick);
}

...

<div
  ref={elemRef}
  dangerouslySetInnerHTML={{ __html: htmlContent }}
/>

6
  • For plain react ie without spfx it works just fine see live codesandbox.io/p/sandbox/event-handler-inner-html-7m7gxz Commented Aug 22 at 9:03
  • The link you shared says "the sandbox.does not exist." Commented Aug 22 at 11:59
  • my bad ... please try now !! Commented Aug 23 at 12:43
  • Great. I see the oclick event is "hardcoded" within the element using the attribute. In this case it works after cloning. Now the next question is what is the element you are copying in SharePoint and how its onclick is defined. Can you update the answer with the sample HTML of this HTML element? Commented Aug 24 at 19:53
  • Thanks ... ELEM is just another Webpart which displays the events from a Calendar Webpart. When a user clicks on an event ,it opens in a new browser tab. Commented Aug 27 at 16:50

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.