How to pass functions as props in React TypeScript
Passing functions as props in React TypeScript:
- Define the type of the function property in the component's interface.
- Define the function in the parent component.
- Pass functions as props to child components.
interface ButtonProps {
sum: (a: number, b: number) => number;
logMessage: (message: string) => void;
// 👇️ turn off type checking
doSomething: (params: any) => any;
}
function Container({sum, logMessage, doSomething}: ButtonProps) {
console.log(sum(10, 15));
logMessage('hello world');
doSomething('abc');
return <div>Hello world</div>;
}
const App = () => {
const sum = (a: number, b: number) => {
return a + b;
};
const logMessage = (message: string) => {
console.log(message);
};
return (
<div>
<Container sum={sum} logMessage={logMessage} doSomething={logMessage} />
</div>
);
};
export default App;
This example shows how to pass functions as props to React components using TypeScript.
sum
The function takes 2 arguments of type number and returns a number.
logMessage
Function takes a string argument and returns nothing.
doSomething
The function is used to demonstrate how to turn off type checking if you don't want to type functions when passing them as props.
any
type effectively turns off type checking, so the function can be passed arguments of any type and can return a value of any type.
This syntax also works if you use a type alias instead of an interface.
type ButtonProps = {
sum: (a: number, b: number) => number;
logMessage: (message: string) => void;
// 👇️ turn of type checking
doSomething: (params: any) => any;
};
It's important that the type of the actual function matches the type we specified in ButtonProps.
If they don't match, we'll get a type checking error.
One common thing we might need to do is pass an event handler function as props
a .
type ButtonProps = {
handleClick: (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
};
function Container({handleClick}: ButtonProps) {
return <div onClick={handleClick}>Hello world</div>;
}
const App = () => {
const handleClick = (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
console.log('element clicked');
};
return (
<div>
<Container handleClick={handleClick} />
</div>
);
};
export default App;
The only difference between this code snippet and the previous one is the type of the event object.
The type varies by element and event (eg onChange, onClick, etc.).
We can determine the type of event by writing the handler function inline and hovering the mouse over the event arguments in the IDE.
interface ButtonProps {
handleClick: (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
}
function Container({handleClick}: ButtonProps) {
// 👇️ wrote event handler inline
return <div onClick={event => console.log(event)}>Hello world</div>;
}
We wrote the event handler function inline and hovered over the event argument to get its type.
Another good way to determine the type of a prop is to right-click it and click Go to Definition in the IDE .
This example shows how we can right-click on an element's style property and determine if its type is CSSProperties
or undefined
.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
How to avoid cross-origin (CORS) issues in React/Next.js
Publish Date:2025/03/17 Views:166 Category:NETWORK
-
In this article, we will introduce how to avoid cross-origin (CORS) issues in React/Next.js. Cross-origin resource sharing (CORS) is a protocol that defines how web requests should be handled when crossing different URLs.
React Tutorial - Transferring Props
Publish Date:2025/03/16 Views:185 Category:React
-
React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.
React Tutorial: Props Anti-Pattern
Publish Date:2025/03/16 Views:183 Category:React
-
React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.
React Tutorial - Props Validation
Publish Date:2025/03/16 Views:99 Category:React
-
Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.
React tutorial: Types of Props for child components
Publish Date:2025/03/16 Views:170 Category:React
-
Usually, the child components of a React component are a group, that is, the child components are an array. Introduction to Type of the Children Props.
How to solve the error Uncaught TypeError: Cannot read properties of undefined in
Publish Date:2025/03/16 Views:150 Category:React
-
In the process of React development, we often encounter some errors. Here we look at an error reported in App.js. The error is as follows: App.js:69 Uncaught TypeError: Cannot read properties of undefined (reading 'setState') at onInput
Why do you need to bind event handlers in React Class Components?
Publish Date:2025/03/16 Views:58 Category:React
-
When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:
Solution to the error "does not contain a default export" in React
Publish Date:2025/03/16 Views:187 Category:React
-
When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.
Error in React: Attempted import error 'X' is not exported from Solution
Publish Date:2025/03/16 Views:76 Category:React
-
In React, the error “Attempted import error 'X' is not exported from” in React.js occurs when we try to import a named import that does not exist in the specified file. To fix the error, make sure the module has named exports and you have not obfu