'Ionic React send Object Prop to Child Component
I just dont get it. I am kinda new to Typescript but used to Code in React.js. I have a simple Component like
const Tab1: React.FC = () => {
const [spices, setSpices] = useState(
[
{
Gewuerz: "pepper",
Gramm: 50,
},
{
Gewuerz: "Tumeric",
Gramm: 870,
},
{
Gewuerz: "salt",
Gramm: 40,
},
{
Gewuerz: "muscat",
Gramm: 9,
}
]);
return (
<IonPage>
<IonHeader>
<IonToolbar>
<IonTitle class="ion-text-center">Spices</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent>
<SpiceList spices={spices}/>
</IonContent>
</IonPage>
);
};
And a Child Component like
interface Props {
spices: Object[];
}
const SpiceList: React.FC<Props> = ({spices}: Props) => {
return (
<IonContent>
<IonList>
{spices.map((e) => <IonItem>{e.Gewuerz}</IonItem>)}
</IonList>
</IonContent>
)
};
export default SpiceList;
I want to render the different Spices inside Prop as a List. I can Map the Prop spices. But i cant access e.Gewuerz as it says it is not available inside of e. So how can i access the SubElements of spices?
EDIT: So it actually works like i tried it. But it always says "Compiled with Errors." If i dismiss it the app renders like i want it to.
Solution 1:[1]
A vague type like object doesn't have any known properties, so Typescript won't let you access any properties on it.
Your spices are all of a specific type { Gewuerz: string; Gramm: number; } so you need to use that type in order to get any useful type information.
You can use that type as-is:
interface Props {
spices: { Gewuerz: string; Gramm: number; }[];
}
But you probably want to create a named type alias. Especially if this Spice object is something that you use throughout your app.
interface Spice {
Gewuerz: string;
Gramm: number;
}
interface Props {
spices: Spice[];
}
Note that you do not need to use React.FC<Props> and ({spices}: Props). You only need one or the other.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Linda Paiste |
