I have created a Component where I am accessing a local json file and passing the array of objects to another component.
Code snippet for the first component -
import statement -
import TvData from './Data/TVData.json';
for the second component I am passing the data like so, I am getting the Error for this line saying
Type '{ data: { id: number; name: string; price: number; imageUrl: string; }[]; }' is not assignable to type 'IntrinsicAttributes & dataProps'.
Property 'data' does not exist on type 'IntrinsicAttributes & dataProps'.
<SecondComponent data={TvData} />
Code Snippet for the second component -
here I defined interface like so,
interface dataProp {
id: number;
name: string;
price : number;
imageUrl : string;
}
type dataProps = dataProp[];
and the functional Component with parameters like so,
function SecondComponent(data: dataProps)
inside which I am mapping through the array of objects from the json file
{
data.map((item : dataProp) =>
{
return (
<Item key={item.id}>
{item.name}
</Item>
)
}
)}
I am new to React with Typescript so any sort of help would be appreciated.
component props must be an object, not an array. Try putting the array inside of one of the input props, like this:
interface Item {
id: number;
name: string;
price : number;
imageUrl : string;
}
type Props = { data: Item[] };
...
function SecondComponent(props: Props) {
return props.data.map(item => (
<Item key={item.id}>
{item.name}
</Item>
));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With