6

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

1 Answer 1

12

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};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.