I have a several classes in a project, created with create-react-app, and I want to pass an array of objects down to child elements, as below.
// Items.tsx
import * as React from 'react';
import ItemTable from './ItemTable';
import { IItem } from './ItemRow';
class Items extends React.Component {
private items = IItem[];
componentWillMount() {
// connect to backend service and retrieve all Items
items = get_items();
}
render() {
return (
<ItemTable items={this.items} />
);
}
}
export default Items;
////////////////////////////////////////////////////////////////
// ItemsTable.tsx
import * as React from 'react';
import { Table } from 'reactstrap';
import ItemRow from './ItemRow';
let ItemTable = (items: IItem[]) => (
<Table>
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Website</th>
</tr>
</thead>
<tbody>
{items.map(item => (
<ItemRow item={item} />
))}
</tbody>
</Table>
);
export default ItemTable;
////////////////////////////////////////////////////////////////
// ItemRow.tsx
import * as React from 'react';
export interface IItem {
name: string;
description: string;
website: string;
}
let ItemRow = (item: IItem) => (
<tr>
<td>{item.name}</td>
<td>{item.description}</td>
<td>{item.website}</td>
</tr>
);
export default ItemRow;
Sadly, during building/compilation I keep getting an error stating that type '{ items: IItem[]; }'
cannot be assigned to type 'items: IItem[]'
. Notice the lack of braces in the second instance when compared to the first.
Either Typescript or React, I assume Typescript, is apparently sticking the array into an object instead of passing the array as I expect it to.
Can anyone figure out what I might be doing wrong here?
You need to pass props to your ItemTable
, not the items directly
let ItemTable = (items: IItem[]) => (
Should be
let ItemTable = (props: {items: IItem[]}) => (
const {items} = props;
Which can also be shortened as
let ItemTable = ({items}: {items: IItem[]}) => (
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