7

How to call function from ".ts" file for button onClick event in tsx file?

enter image description here

this is my function in ts file:

public button_click(): void {
   alert("CLICKED!");
}

enter image description here

9

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>
  • Is this the best way to do it? – Goshky Aug 5 '17 at 9:40
1

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. enter image description here

Output :

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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