Toto NaBendo
Toto NaBendo

Reputation: 342

ForwardRef on a custom component typescript

I'm trying to access a children component function from his parent using references.

I've my parent component :

const Parent: FC = (props) => {
    let childRef = useRef(null);

    const handle = () => {
        childRef.current.customFunction();
    }

    return (
        <Children props1="value" ref={childRef}/>
        <Button onPress={handle}/>
}

And my children component :

interface Props {
    props1: string
}

const Children: FC<Props> = forwardRef((props,ref) => {
    const customFunction = () => {
        console.log("Custom");    
    }

    return <View>props.children</View>
})

I have a typescript error when rendering my children component :

Property 'ref' does not exist on type 'intrinsicAttribute & props & {children?:ReactNode}

Note that I would like to keep any strict type.

Upvotes: 1

Views: 4715

Answers (1)

You are missing some types on the way.

interface Handles {
    customFunction: ()=>void
}
interface Props {
    props1: string
}

const component: RefForwardingComponent<Handles, Props> = (props,ref) => {

    useImperativeHandle(ref, () => ({
        customFunction: () => {
            console.log("Custom");    
        }
    }));

    return <View>props.children</View>
};
const Children = forwardRef(component)


Upvotes: 6

Related Questions