Reputation: 65
I'm trying to pass a function as a prop to a child component in React but TypeScript is giving me errors. I have a function as such:
const submitData = (title: string, year: string): void => {
// DO STUFF
};
// PASS IT TO CHILD
<ChildComponent
submitData={submitData("do", "stuff")}
/>
And in my Child component I pass the type and add it like such:
interface ChildComponentProps {
submitData: (a: string, b: string) => void,
};
const ChildComponent: React.FC<ChildComponentProps> = ({submitData}) => {
return (
<div>
<form onSubmit={() => submitData("stuff", "do")}>
//// etc. etc. etc.
</div>
)
};
I keep getting an error at the line where I pass it to the child component. It says:
Type 'void' is not assignable to type '(a: string, b: string) => void'.
Clearly the original submitData-function is not of type "void"
but a function with two parameters. What am I doing wrong?
Upvotes: 1
Views: 2123
Reputation:
You aren't passing the submitData function as a prop. You are passing the result of calling submitData. Simply change it to
<ChildComponent
submitData={submitData}
/>
Upvotes: 2