Home > Blockchain >  Send onClick function as props to a component in React with Typescript
Send onClick function as props to a component in React with Typescript

Time:12-08

I'm new to Typescript and I have to write a parent component that sends as props onClick to the child component where is a button that triggers the functionality of onClick when clicked.

Here is the code:

export function ParentComponent(props: ParentComponentProps) { 
  const [isOpened, toggleModal] = useToggle(false);
 // useToggle is a custom hook that toggles a boolean
  ...
  const onClick = () => {
    toggleModal();
  }

  return (
          <ChildComponent onClick={onClick} />
         );
}

For the child component I don't know how to define the interface, what should be put here?

export interface ChildComponentProps {
   onClick: <unknown>();  // what to add here?
}

And here is the child component:

export function ChildComponent({onClick}: ChildComponentProps) {
   ...
   return ( 
            <div>
            ...
               <ButtonComponent 
                  onClick={() => onClick()}
                  ...
               />
            ...
           );
}

Any ideas what to add to the interface or if there should be any other changes to be Typescript correct?

CodePudding user response:

For functions like onClick, you have to describe input arugments and output or just write Function (although for better type checking you shouldn't just write Function).

So something like this:

onClick: () => void

If for example your function gets a number and returns a string, you should write it like this:

onClick: (n: number) => string

CodePudding user response:

Parent Component:

interface OnClickIdInterface {
    (): void,
}

export interface parentPropsInterface {
    onClick?: OnGetIdInterface;
}
 
render() {
    return <ChildComponent onClick={(id) => this.onClick(id)}/>
 }

Child Component:

const HomePresentation: React.FunctionComponent<parentPropsInterface> = ({onClick}) => {
    return (
        <div onClick={()=>onClick()}>
           some content
        </div>
    )
}

CodePudding user response:

Following code should work. But it depends on ButtonComponent. Used React.MouseEventHandler<T = Element> as type.

export interface ChildComponentProps {
   onClick: React.MouseEventHandler<ButtonComponent>
}

export function ChildComponent({onClick}: ChildComponentProps) {
   ...
   return ( 
            <div>
            ...
               <ButtonComponent 
                  onClick={() => onClick()}
                  ...
               />
            ...
           );
}

Please notify me if this is incorrect.

  • Related