skip to Main Content

App.tsx

export default function FilterableProductTable() {
  const products: Product[] = [
    { category: "Fruits", price: "$1", stocked: true, name: "Apple" },
    { category: "Fruits", price: "$1", stocked: true, name: "Dragonfruit" },
    { category: "Fruits", price: "$2", stocked: false, name: "Passionfruit" },
    { category: "Vegetables", price: "$2", stocked: true, name: "Spinach" },
    { category: "Vegetables", price: "$4", stocked: false, name: "Pumpkin" },
    { category: "Vegetables", price: "$1", stocked: true, name: "Peas" },
  ];
  return (
    <>
      <Testing data={products} />
    </>
  );
}

interface Product {
  category: string;
  price: string;
  stocked: boolean;
  name: string;
}


function Testing(data: Product[]) {
  return <p>{data[0].category}</p>;
}

The error arises from the "Testing" function call declaration. I don’t know what is the problem. I tried searching it up, but couldn’t figure it out. Iam a beginner.

I tried running the code from a typescript playground and it is working perfectly. But this is a React + Typescript environment and it shows me error.

2

Answers


  1. TypeScript expects that the prop data to be defined, however, you have not defined a prop, instead, you are directly accessing data as if it were a prop.

    function Testing({ data }: { data: Product[] }) {
      return <p>{data[0].category}</p>;
    }
    
    Login or Signup to reply.
  2. This is not how you pass props to a component. You should do it that way:

    export default function FilterableProductTable() {
      const products: Product[] = [
        { category: "Fruits", price: "$1", stocked: true, name: "Apple" },
        { category: "Fruits", price: "$1", stocked: true, name: "Dragonfruit" },
        { category: "Fruits", price: "$2", stocked: false, name: "Passionfruit" },
        { category: "Vegetables", price: "$2", stocked: true, name: "Spinach" },
        { category: "Vegetables", price: "$4", stocked: false, name: "Pumpkin" },
        { category: "Vegetables", price: "$1", stocked: true, name: "Peas" },
      ];
      return (
        <>
          <Testing data={products} />
        </>
      );
    }
    
    interface Product {
      category: string;
      price: string;
      stocked: boolean;
      name: string;
    }
    
    interface Props {
      data: Product[];
    }
    
    
    function Testing(props: React.PropsWithChildren<Props>) {
      return <p>{props.data[0].category}</p>;
    }
    

    In general, when you pass data through custom attributes to your component, the data stored by its key name in the component function parameter, which we call props as a convention. Then you can access the value by access the attribute name.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search