Property 'name' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Product> & Readonly<{}>'

Viewed 43

First time using react and don't understand what's the problem here. Any help would be appreciated. I have imported the files correctly still not able to solve this error:

Property 'name' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Product> & Readonly<{}>'
import { Component } from "react";
import Product from "./product";
export default class Shopping extends Component {
  state = {
    products: [
      {
        id: 1,
        name: "Laptop",
        price: "8000",
        photo: "https://picsum.photos/id/1010/60",
        quantity: 4,
      },
      {
        id: 2,
        name: "HeadPhone",
        price: "9000",
        photo: "https://picsum.photos/id/1011/60",
        quantity: 7,
      },
    ],
  };
  render() {
    return (
      <div>
        <h4>Shopping Cart</h4>
        <div>
          {this.state.products.map((prod) => {
            return <Product key={prod.id} name={prod.name} />; // this is where I am getting the error
          })}
        </div>
      </div>
    );
  }
}
1 Answers

You can define the types for the state.

https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/class_components/

//shopping.tsx

import { Component } from "react";
import Product from "./product";
type MyProps = {
  // using `interface` is also ok
};

type ProductTye ={    
  id: number,
  name: string, 
  price: string,
  photo: string,
  quantity: number
 }
type MyState = {
  products:ProductTye[]
};
export default class Shopping extends Component<MyProps, MyState> {

  state : MyState={
   products:[
    {    
    id: 1,
    name: "Laptop", 
    price:"8000",
    photo:"https://picsum.photos/id/1010/60",
    quantity:4
    },
    {id:2,name:"HeadPhone", price:"9000",
     photo:"https://picsum.photos/id/1011/60",
     quantity:7}]
    }
   render(){
    return(
     <div>
       <h4>Shopping Cart</h4>
      <div>
        {this.state.products.map((prod)=>{
            return ( <Product 
            key={prod.id}
            name={prod.name}
            quantity={prod.quantity} />);// this is where I am getting the error
           })}
        </div> 
     </div>
    )}


    }
//product.tsx

export default function Product({
  name,
  quantity
}: {
  name: string;
  quantity: number;
}) {
  return (
    <div className="App">
      <h1>
        {name} {quantity}
      </h1>
    </div>
  );
}


Related