Using React with Typescript: How to pass a function as a prop to a child component and call it from within

I am trying to pass a function as a prop to a child component so that the child can call it. Here is my parent component:

interface DateValue {
  dateValue: string;
}

const Page: React.FC = () => {
    
  const dateChanged = (value: DateValue) => {
    console.log(value);
  }

  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonButtons slot="start">
            <IonMenuButton />
          </IonButtons>
          <IonTitle>Financial Records</IonTitle>
        </IonToolbar>
      </IonHeader>

      <IonContent fullscreen>
        <IonHeader collapse="condense">
          <IonToolbar>
            <IonTitle size="large">Financial Records</IonTitle>
          </IonToolbar>
        </IonHeader>
        <DateContainer onChanged={e => dateChanged} />
      </IonContent>
    </IonPage>
  );
};

export default Page;

And here is my child component:

interface Prop {
  onChanged: (date: string) => void
}

const DateContainer: React.FC<Prop> = (prop: Prop) => {

  const [currentDate, setCurrentDate] = useState<string>(moment().toISOString());
  const picker = createRef<HTMLIonDatetimeElement>();

  const dateChanged = (value: string) => {
    setCurrentDate(value);
    prop.onChanged(value);
  }

  const openPicker = () => {
    picker.current?.open();
  }

  return (
    <div className="DateContainer">
      <div className="header">
        <h3 className="title"><IonDatetime onIonChange={e => dateChanged(e.detail.value!)} ref={picker} value={currentDate} /> <IonIcon onClick={openPicker} className="icon" ios={calendarOutline} md={calendarSharp} /></h3>
      </div>
    </div>
  );
};

export default DateContainer;

However, when the child calls prop.onChanged(value);, it does not trigger the function from the parent:

const dateChanged = (value: DateValue) => {
    console.log(value);
}

I must have made a mistake somewhere. Can you help me figure out what went wrong?

Answer №1

Make sure to invoke your function in the parent component. Here's one way to do it:

<DateContainer onChanged={e => dateChanged(e)} />

Alternatively, you can directly pass the function reference like this:

<DateContainer onChanged={dateChanged} />

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method for obtaining a literal type through a function parameter to use as a computed property name?

Can you help me with this code snippet? const fn = (name: string) => { return { [name]: "some txt" }; }; const res = fn("books"); // books or any other string The type of res recognized by TS is: const res: { [x: string]: string ...

Convert JSON data into an array of strings that are related to each other

I'm encountering an issue with converting JSON into a string array I must convert a JSON into a string array to dynamically INSERT it into our database, as I need this to work for any type of JSON without prior knowledge of its structure. Here is th ...

Verification for collaborative element

I am currently working on creating a shared component for file uploads that can be reused whenever necessary. Interestingly, when I include the file upload code in the same HTML as the form, the validation functions properly. However, if I extract it into ...

Nested modal in native app utilizes the React Carbon TextInput component for an uneditable input field

As a newcomer to React, I have encountered an issue with the Tauri framework used to bundle my React application as a desktop app. Specifically, I am facing a problem where the TextInput field, nested inside a modal and utilizing React Carbon components, i ...

Issue with Loosing Focus in React TextInput when typing the letter "S"

My TextInput is acting strangely - it loses focus only when I type the letter s. All other letters work fine. <FormControl key={"1"} sx={{ m: 1 }} variant="outlined" onChange={handleFilterValueChange}> <InputLabel htmlFor=& ...

What improvements can I implement in this React Component to enhance its efficiency?

Seeking advice on improving the efficiency of this React Component. I suspect there is code repetition in the onIncrement function that could be refactored for better optimization. Note that the maxValue prop is optional. ButtonStepper.tsx: // Definition ...

React Material UI Select component is failing to recognize scrolling event

Having some difficulty understanding how to detect a scroll event with a Select component using Material-UI. The Select has MenuProps={...}, and I want to listen for the scroll event inside it. I've tried putting onScroll within MenuProps={...}, but ...

The command "npm start" is malfunctioning

Here is the content of my package.json file: { "name": "application", "version": "1.0.0", "private": true, "scripts": { "start": "node node_modules/react-scripts/scripts/start.js", "test": "react-scripts test" }, "dependencies": { ...

What are the steps to display 10 items sequentially with the angular2-infinite-scroll package?

I'm currently working with the angular 2 infinite scroll module and I need to display 10 elements at a time. When the user scrolls down, the next 10 elements should be shown and the scrollbar should adjust accordingly. I've tried several methods ...

What is the solution for the error stating "Unable to locate a declaration file for the module 'request-context'."?

I am currently working on three different files: index.js, index.main.js, and app.js. My goal is to use request-context to extract a variable from index.main.js and pass it to index.js. Within my app.js file, located in the server folder, I have the follo ...

Tips on filtering an array in a JSON response based on certain conditions in Angular 7

Looking to extract a specific array from a JSON response based on mismatched dataIDs and parentDataIDs using TypeScript in Angular 7. { "data":[ { "dataId":"Atlanta", "parentDataId":"America" }, { "dataId":"Newyork", ...

Do Typescript interfaces check method parameters for validation?

interface optionsParameter { url: string; } function DEC(options: optionsParameter){ } DEC(2) //typescript check compilation error let obj:any = { name: "Hello" } obj.DEC = function(options: optionsParameter){} obj.DEC(1); // no compilation ...

Utilize the up and down arrow keys to scroll through a description list in React

If you want to navigate through the list of Description Details using the tab and shift tab keys, it can be done easily. The default behavior allows for smooth navigation. <dl> <dt style={{ textAlign: "center" }}>Beast of Bodmin< ...

Spring Boot fails to recognize path variable data sent from Angular

When working with Angular 7, I encountered a situation where I needed to pass a value from the service class of Angular. Here is how I achieved it: executeHelloWorldBeanServiceWithPathVariable(name){ console.log("name coming from here"+name); retu ...

Obtain the parameters of a function within another function that includes a dynamic generic

I am attempting to extract a specific parameter from the second parameter of a function, which is an object. From this object, I want to access the "onSuccess" function (which is optional but needed when requested), and then retrieve the first dynamic para ...

Can anyone provide guidance on incorporating jQuery typing into an angular2 seed project?

I'm struggling to incorporate jQuery typings into my Angular2-seed project. Within my component, I am utilizing jQuery in the following manner: declare let $: any; export class LeafletComponent implements OnInit { ngOnInit(): void { th ...

Updating Angular 9 values using a fixed object

I am dealing with a patch value here where I simply pass an object to it. this.formPesquisar.controls['daniloTeste'].patchValue(this.dadosVisualizar.daniloTeste); However, I would like to pass a static object instead, something like: this.formPe ...

When modifying the state of an array within a component, certain values may be overwritten and lost in the process

Currently, I'm faced with the challenge of ensuring that a component displays a loading screen until all images have completed loading. This is necessary because there are approximately 25 images that must finish loading before the page can be display ...

Where does tsc retrieve its definitions from when utilizing npm definitions?

After transitioning from using typings to just relying on npm, I noticed that the @types directory in node_modules is present, but there are no additional files required. Previously with typings, I always had to include the index.d.ts file within the typi ...

Error encountered when providing valid data types as arguments in a React/Typescript function

I am facing an issue when passing a string variable to a function. To address this, I have created an interface called MyMessageProps where I declare the message as a string. Subsequently, the function MyMessage utilizes this interface to return with the ...