0

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

1
  • What have you tried so far? Commented Nov 16, 2021 at 7:42

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

what will be the modification in above code if I want to pass state
you can simply pass the state with some name <Button name={stateValue}> and use it in your child component.
@SanketPatil can you please accept this answer, so in future other can easily read it. Thank you.
-1

Basically it is simple:

let my_function = () => {console.log('hi!')}

you just have to pass it as an argument:

return (
<>
<MyAnotherComponent my_function={my_function}></MyAnotherComponent>
</>
)

and inside MyAnotherComponent you can call it like:

props.my_function()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.