Home > Mobile >  Type error trying to pass an array of interfaces as a prop
Type error trying to pass an array of interfaces as a prop

Time:12-05

I am trying to pass array of interfaces that are stored in a useState hook to a child functional component.

Here is the hook. It only becomes populated after user interaction:

  const [districtData, setDistrictData] = useState<DistrictData[]>([]);

Here is the interface which is imported into the parent tsx file.

export interface DistrictData {
  lng: number,
  lat: number,
  id: string }

Here is where I pass it to the child component <ListOfSchools/> THIS is the line where TS is giving the error.

 <ListOfSchools districtData={districtData} />

This is what the child component ListOfSchools.tsx looks like:

import { DistrictData } from "@utils/nces";

interface Props {
  propWhichIsArray: DistrictData[];
}

export const ListOfSchools: React.FC<Props> = ({ propWhichIsArray }) => {
  return <div></div>;
};

Here is the error I am getting:

Type '{ districtData: DistrictData[]; }' is not assignable to type 'IntrinsicAttributes & Props & { children?: ReactNode; }'.
  Property 'districtData' does not exist on type 'IntrinsicAttributes & Props & { children?: ReactNode; }'.

I believe the goal is the set the prop to be of the type that the child component expects.

I have also tried below, along with many other attempts from stackoverflow articles:

export const ListOfSchools: React.FC<DistrictData[]> = ({ props: DistricData[] }) => {
  return <div></div>;
}; 

Thank you very much for any help here.

CodePudding user response:

Based on the code you've provided, it looks like you're trying to pass the districtData prop to the ListOfSchools component, but you're trying to access it as propWhichIsArray in the child component.

To fix the error you're getting, you'll need to make sure that the prop name you're using in the child component matches the name of the prop you're passing from the parent. In this case, you can either change the name of the prop in the parent component when you pass it, like this:

<ListOfSchools propWhichIsArray={districtData} />

Or, you can change the name of the prop in the child component to match the name that it's being passed with and update the type accordingly, like this:

import { DistrictData } from "@utils/nces";

interface Props {
  districtData: DistrictData[];
}

export const ListOfSchools: React.FC<Props> = ({ districtData }) => {
  return <div></div>;
};
  • Related