I’m trying to pass props from my AllProducts, MenProducts etc. components to AddToCartButton component so that I can reuse AddToCartButton component. If I try to pass props like
<AddToCartButton id={product.id} />
I’m getting error:
Type ‘{ id: number; }’ is not assignable to type ‘IntrinsicAttributes’.
Property ‘id’ does not exist on type ‘IntrinsicAttributes’.ts(2322)
I’ve also tried to pass simple string as prop but it gives me the same error.
import { useEffect } from 'react'
import { Link } from 'react-router-dom'
import { useAppSelector, useAppDispatch } from '../hooks/hooks'
import { fetchAllProducts } from '../store/features/allProducts/allProductsSlice'
import AddToCartButton from '../components/AddToCartButton'
export const AllProducts = () => {
const product = useAppSelector(state => state.product);
const dispatch = useAppDispatch();
useEffect(() => {
dispatch(fetchAllProducts())
}, [dispatch])
return (
<div className="products-wrapper">
<h1 className="products-wrapper__heading">
All Products
</h1>
<div className="products-wrapper__products-cards-wrapper">
{product.products.map(item => (
<div key={item.id} className="product-card">
<Link to={`/product/${item.id}`} className='products-wrapper__product-link'>
<div className="product-card__img-wrapper">
<img src={item.image} alt="product" className="product-card__product-img" />
</div>
<h3 className="product-card__product-name">
{item.title}
</h3>
<h4 className="product-card__product-price">
{item.price} €
</h4>
</Link>
<AddToCartButton id={item.id}/>
</div>
))}
</div>
</div>
)
}
export default AllProducts
2
Answers
Mistake was in AddToCartButton component. I didn't define prop type in AddToCartButton component. Thank You all from your comments.
The error you’re encountering is related to TypeScript and the way you’re passing props to your AddToCartButton component. It seems that TypeScript is not recognizing the id prop in the AddToCartButton component.
// AddToCartButton.tsx
In this example, we’ve defined an interface AddToCartButtonProps to specify the expected prop types for AddToCartButton. It includes an id prop of type number. Adjust the interface to include any other props your AddToCartButton component may need.
In your AllProducts component, make sure you import and use the AddToCartButton component correctly: