Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs/Typescript cannot pass array of items as property to child

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?

like image 951
Chris Bond Avatar asked Dec 14 '17 02:12

Chris Bond


1 Answers

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[]}) => (
like image 157
klugjo Avatar answered Nov 04 '22 16:11

klugjo