JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > React >

How to pass functions as props in React TypeScript

Author:JIYIK Last Updated:2025/03/17 Views:

Passing functions as props in React TypeScript:

  1. Define the type of the function property in the component's interface.
  2. Define the function in the parent component.
  3. 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.

sumThe function takes 2 arguments of type number and returns a number.

logMessageFunction takes a string argument and returns nothing.

doSomethingThe function is used to demonstrate how to turn off type checking if you don't want to type functions when passing them as props.

anytype 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 propsa .

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>;
}

react gets the event type

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 .

style prop css properties

This example shows how we can right-click on an element's style property and determine if its type is CSSPropertiesor 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.

Article URL:

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.

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.

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial