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.
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.
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.
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> ); ...
// 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).
<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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With