Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a function as an argument to a ReactJS component in TypeScript

Tags:

I am trying to make a reusable ReactJS button component and need help on how to pass a function to a component and then use it as a click event. The click event on the button is not working.

Here is the code that will call the component:

export var MyPublicFunction = function (inArg: number) {     alert(inArg); }  ReactDOM.render(<MyButton name="My Button" clickFunction={MyPublicFunction(1)} >Button</MyButton>, document.getElementById('content')); 

Here it the component I'm trying to write:

interface myProps {    name: string;    clickFunction: any }  class MyButton extends React.Component<myProps, {}> {      constructor(props: myProps) {         super(props);     }      render() {         return (<div>             <button ref="btn1"  onClick={this.props.clickFunction} >                 {this.props.name}              </button>         </div>);     } //end render. } //end class. 
like image 824
Lambert Avatar asked Feb 12 '16 17:02

Lambert


People also ask

How do you pass a function to a component React TypeScript?

To pass a function as props in React TypeScript: Define a type for the function property in the component's interface. Define the function in the parent component. Pass the function as a prop to the child component.

How do you pass a function as an argument TypeScript?

Similar to JavaScript, to pass a function as a parameter in TypeScript, define a function expecting a parameter that will receive the callback function, then trigger the callback function inside the parent function.

How do you pass a function as an argument in React?

In order to pass a value as a parameter through the onClick handler we pass in an arrow function which returns a call to the sayHello function. In our example, that argument is a string: 'James': ... return ( <button onClick={() => sayHello('James')}>Greet</button> ); ...

How do you define a function in React TypeScript?

// Easiest way to declare a Function Component; return type is inferred. const App = ({ message }: { message: string }) => <div>{message}</div>; Tip: You might use Paul Shen's VS Code Extension to automate the type destructure declaration (incl a keyboard shortcut).


1 Answers

<MyButton name="My Button" clickFunction={MyPublicFunction(1)} > 

The expression MyPublicFunction(1) is immediately invoked during evaluating of the containing expression. What you want is to provide a function to clickFunction:

<MyButton name="My Button" clickFunction={() => MyPublicFunction(1)} > 

Note that you would get a type error if you had written something like this:

interface myProps {    name: string;    clickFunction: () => void; } 
like image 127
Ryan Cavanaugh Avatar answered Oct 04 '22 07:10

Ryan Cavanaugh