How to call function from ".ts" file for button onClick event in tsx file?
this is my function in ts file:
public button_click(): void {
alert("CLICKED!");
}
Add a property to your IAutoCompleteProps
interface for your click handler. Then pass the function from the AutoCompleteWebPart into the interface as one of the component's properties.
So in your IAutoCompleteProps something like this:
export interface IAutoCompleteProps {
//Other properties
clickHandler: () => void;
}
Then in your AutoCompleteWebPart render:
public render(): void {
const element: React.ReactElement<IAutoCompleteProps > = React.createElement(
AutoComplete,
{
//Other props
clickHandler: this.button_click
}
);
ReactDom.render(element, this.domElement);
}
Then in your AutoComplete component JSX portion:
<button onClick={this.props.clickHandler}>CLICK ME</button>
You can use the below sample which I have created using SPFx. Update the Render method and add a button with the onClick event in the React tsx file as shown below :
public render(): React.ReactElement<IReactGetItemsProps> {
return (
<div className={styles.panelStyle} >
<br></br>
<br></br>
<div className={styles.tableCaptionStyle} > Demo : Retrieve SharePoint List Items using SPFx , REST API & React JS </div>
<br></br>
<div >
<button id="AlertMe" type="submit" onClick={this.AlertMe} >AlertMe</button>
</div>
</div>
);
}
AlertMe()
{
alert("You have clicked Alert!");
}
This adds the click event attribute to the button 'AlertMe'. On clicking it, the AlertMe method is called.
Output :