how can I pass a useState props using TypeScript to a child component

Issue

being new to Typescript in react application, I am trying to describe a JavaScript object using TypeScript. This object will be utilized in a useState hook, and then passed on to a child component.

I have created my interface like so :

export interface IformEntry {
  type:string;
  toFrom:string;
  details:string;
  amount:number
}

Then here is my Home component which contains the state ( I simplified the code to get to the point )

import FormulaireFooter from "../components/FormulaireFooter";
import { IformEntry } from "../interfaces/IformEntry";
import { useState } from "react";

export default function Home() {

 const [formEntry, setformEntry] = useState<IformEntry | undefined>(undefined);
 
  return (
    <>
      <FormulaireFooter
        setformEntry={setformEntry}
        formEntry={formEntry}
      />
    </>
  )
}

and here is the formulaireFooter.tsx file, which is the child component I am passing the state to :

import { IformEntry } from "../interfaces/IformEntry";

const FormulaireFooter = ({
  setformEntry,
  formEntry,
}
:{
  setFormEntry: any;
  formEntry: IformEntry;
  setFormList: any;
  formList: any;
}
) => { 
// TODO
}

so, what I am not fully understanding, is how I should redefine my useState hook in my child component?

because in the child component I get that message when I hover over my setFormEntry property:
enter image description here

Solution

You’ve declared the useState saying it can either be IFormEntry or undefined. In the props of the child component, you have only said it can be IFormEntry. These don’t match, which is why typescript is complaining.

You’ll need to make the two types agree somehow.

One option would be to change the props definition to allow undefined as well.

const FormulaireFooter = ({
  setformEntry,
  formEntry,
}
:{
  setFormEntry: any;
  formEntry: IformEntry | undefined; // <-- allow the same types here
  setFormList: any;
  formList: any;
}
) => { 
// TODO
}

Another option, which is the one I would suggest, is to make better default value for your state.

const defaultState: IFormEntry = {
  type: '';
  toFrom: '';
  details: '';
  amount: 0
}

const [formEntry, setformEntry] = useState<IformEntry>(defaultState);

Answered By – Brian Thompson

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published