Search code examples
reactjsreact-typescript

Proper way of passing function from one component to other on React typescript


I am new to typescript, I was facing problems while passing the function of the parent component as a prop to another component, I searched online but nothing was useful

For reference, I am attaching JSX Code here, [TSX is what I wish]

This is parent component

export default function Notification() {
    const [notification, setnotification] = useState(['alert', 'booking'])

    return (
        <div>
            <ShowNotification setnotification={setnotification} notification={notification} />
        </div>
    )
}

This is child component

const ShowNotification = ({notification,setnotification}) => {
    notification.map((item, index) => {
        <li>item</li>
    })
}

The main issue for me is specifying prop types in typescript


Solution

  • There are few stackoverflow answers, which may help you.

    But in summary, It's same as like passing other normal props.

    Here is the basic example which may help you to understand:

    // button.tsx
    interface IProps {
      children: React.FC | string;
      onClick: (e: any) => void;
      type: "button" | "reset";
    }
    
    const Button: React.FC<IProps> = (props) => {
      return (
        <button type={props.type} onClick={props.onClick}>
          {props.children}
        </button>
      );
    };
    
    export default Button;
    
    import Button from "./button";
    
    export default function App() {
      const myFunction = (e: any) => {
        console.log("Event is: ", e);
      };
    
      return (
        <Button type="button" onClick={myFunction}>
          Click Me
        </Button>
      );
    }
    

    In here, you can see, I've passed the myFunction to the Button component as a props, and call that method from the ButtonComponent itself, Whenever someone press the button, it execute the myFunction method from the parent App.tsx file.