Bill
Bill

Reputation: 5150

React Typescript: Pass value from child to parent

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')
}

Upvotes: 1

Views: 5807

Answers (2)

tony
tony

Reputation: 1326

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!

Upvotes: 0

Sunil Chaudhary
Sunil Chaudhary

Reputation: 4743

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')
}

Upvotes: 1

Related Questions