How to add event listener for button click in SPFX webpart
Scenario – Supposed you are developing a SPFx webpart. Part of requirement is to get data from user, so a basic input form and a button. On click of button you wanted to call run your custom code, may be saving data to SP via REST API or anything.
In this article, we will see how to add html input controls like textarea and a button. On click of button we wanted to read data from input controls and use this user inputed data as per our requirement.
This article assumes, you have already created SPFx webpart without any javascript framework selected. You would see render method in you WebPart.ts file.
public render(): void { // HERE WE ARE ADDING TEXT AREA CONTROL. this.domElement.innerHTML += '<textarea id ="headerText" rows = "5" cols = "50" name = "description">Enter Header HTML</textarea>'; this.domElement.innerHTML += '<button type="button" id="btnRegister">Click Me!</button>'; this._setButtonEventHandlers(); } private _setButtonEventHandlers(): void { const webPart: WpConfigureApplicationCustomizerWebPart = this; this.domElement.querySelector('#btnRegister').addEventListener('click', () => { var headtext = document.getElementById("headerText")["value"] ; alert(headtext); }); }
Some notes in above code
- If you use onclick event in button html control and then try to call your custom javascript function, it will not execute because browser will block it with below error. That is the reason we have to use another approach to add event listener to button.
Refused to execute inline event handler because it violates the following Content Security Policy directive: “default-src ‘self’ blob: filesystem: chrome-extension-resource:”. Either the ‘unsafe-inline’ keyword, a hash (‘sha256-…’), or a nonce (‘nonce-…’) is required to enable inline execution. Note also that ‘script-src’ was not explicitly set, so ‘default-src’ is used as a fallback.
- To get instance of input control, you have to go with traditional javascript but to read value it has to be accessed by properties array like below. We cannot access it with ‘.value’ way.
var headtext = document.getElementById(“headerText”)[“value”] ;
- This solution is using no javascript framework. With react and knockout js it would be different.
- This might be one of solution, there may be some other ways. Please comment if you find any other way.
Hope this helps…Happy coding..!!!