1

I want to be able to call a function printUrl from the child component. I am passing the function in a prop called theurl I don't know how to declare this prop type, I cant leave it as any in the child's interface and then when I do call printUrl('testing') nothing gets logged. I am expecting the parent function printUrl to log out testing

I get the feeling that I've completely misunderstood how to pass values up. The error I get is Unhandled Rejection (ReferenceError): printUrl is not defined

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

const Parent: React.FC = () => {
    const printUrl = (arg: string) => {
        console.log(arg)
    }
    return (
    <Child theurl={printUrl}/>
    )
}

and the child is like...

import React from 'react';

interface PropsInterface {
  theurl: any;
}
const Child: React.FC<PropsInterface> = (props: PropsInterface) => {
 printUrl('testing')
}

2 Answers 2

1

When you are passing the props here at <Child theurl={printUrl}/>, the printUrl is renamed to theurl. So, in the child component, you need to access it by name of theurl.

So, you need to access it by theurl('testing') and it should work fine.

Hope it helps!

Edit: Modifying the answer as per discussion. You can access it as props.theurl in the component:

const Child: React.FC<PropsInterface> = (props: PropsInterface) => {
 props.theurl('testing')
}
Sign up to request clarification or add additional context in comments.

4 Comments

The error I get is Cannot find name 'theurl'.ts(2304)
props.theurl('testing') worked, any idea on the correct type in the interface?
Try using props.theurl.
interface PropsInterface { theurl: Function; }
0

printUrl gets assigned to the child member theurl. In the child you want to reference it like so:

const Child: React.FC<PropsInterface> = (props: PropsInterface) => {
 props.theurl('testing')
}

You can also strongly type theurl as a function:

interface PropsInterface {
  theurl: (url:string) => void;
}

Child is implicitly returning void which is can't be the return type of a React component. null is though:

const Child: React.FC<PropsInterface> = (props: PropsInterface) => {
 props.theurl('testing'); return null;
}

It is good practice to name function props as a verb.

import React from 'react';

interface PropsInterface {
  printUrl: (url:string) => void;
}

const Child: React.FC<PropsInterface> = (props: PropsInterface) => {
  props.printUrl("testing"); return null;
}


const Parent: React.FC = () => {
    const printUrl = (arg: string) => {
        console.log(arg)
    }
    return (
    <Child printUrl={printUrl}/>
    )
}

Good luck on your typescript adventures!

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.