Search code examples
typescriptreact-nativeionic-react

React Typescript: Passing function as prop to child and call it from the child


I need to pass function as prop to child, then the child needs to call it.

Here is my parent:

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:

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;

When the child calls prop.onChanged(value); from:

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

It does not call:

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

From the parent.

What did I do wrong here?


Solution

  • You don't call your function in the parent. Use like this

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

    Or

    <DateContainer onChanged={dateChanged} />