Bill
Bill

Reputation: 5150

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};

Upvotes: 6

Views: 11360

Answers (1)

Andrew
Andrew

Reputation: 7545

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};

Upvotes: 12

Related Questions