Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passed onClick function not identified as a function

I am passing an onClick function as a prop in my react app from one component to another. It gives an error which shows as Uncaught TypeError: handleOnClick is not a function . Here is my function which i am passing through,

propList = ['a', 'b', 'c']

const handleOnClick = (propArr: any) => {
    console.log('propArr===>', propArr)
}

<ChildComponent handleOnClick ={handleOnClick } propList={propList}/>

Here is the component which takes those props,

export const ChildComponent = (propList: any, handleOnClick : any) => {

const handleSubmit = () => {
    handleOnClick ('pass this to parent!')
}
   return(
       <button onClick={handleSubmit}>Submit</button>
   )
}

Do i need to change something specifically to overcome this situation?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is incorrect:

export const ChildComponent = (propList: any, handleOnClick : any) => {
    // ...
};

Components take props as a single parameter which is an object. So at a minimum that should be:

export const ChildComponent = ({ propList, handleOnClick } : any) => {
    // ...
};

That uses destructuring in the parameter list to pick the propList and handleOnClick properties from the first parameter’s value.

But there’s no point in using TypeScript if you’re just going to use the any type. Better to properly define a typed props interface for the component, and use that. For instance:

type ChildComponentProps = {
    propList: AppropriateTypeHere[];
    handleOnClick(propArr: AnotherAppropriateTypeHere[]): void;
}
export const ChildComponent = ({ propList, handleOnClick } : ChildComponentProps) => {
    // ...
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading