Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React TypeScript Passing a function to child component

Im trying to pass a function to a child component, but im getting a number of typescript errors...

parent.tsx

import React from 'react';
import {Child} from './child';

const Parent: React.FC = () => {
    function fire() {
        console.log('fire')
    }

    return (
        <Child fire={fire}/>
//         ^___ error here!
    )
}

The error on fire is Type '{ fire: () => void; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'. Property 'fire' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'.ts(2322)

child.tsx

import React from 'react';
const Child: React.FC = (props: any) => {
    return (
        <p onClick={props.fire}>Click Me</p>
    )
}
export {Child};
like image 782
Bill Avatar asked Sep 04 '26 02:09

Bill


1 Answers

You're adding your type in the wrong location. If you hover over React.FC you'll see that it accepts an argument and that the default value is {}, meaning no props that aren't available by default (like props.children). Add that argument.

Assigning the type in the argument as (props: any) doesn't provide that type information. You can leave it out when you define that argument in React.FC

import React from 'react';
interface ChildProps {
   fire: () => void
}
const Child: React.FC<ChildProps> = (props) => {
    return (
        <p onClick={props.fire}>Click Me</p>
    )
}
export {Child};
like image 80
Andrew Avatar answered Sep 06 '26 18:09

Andrew