I am trying to send some props to my another component but it is giving this error:

1 Answer
I'm assuming you're not declaring AddToCart's props properly (no pun intended).
Your code should look something like this:
type Book = {
title: string;
author: string;
description: string;
};
type CartProps = {
book: Book;
};
// btw: components (and their names) should represent *things* not actions
const AddToCart = ({ book }: CartProps) => {
// ^^^^^^^^^
return (
<div>
<h1>{book.title}</h1>
<h2>{book.author}</h2>
<p>{book.description}</p>
</div>
);
};
export default function App() {
const book = {
title: "Some Title",
author: "John Smith",
description: "Book description."
};
return <AddToCart book={book} />;
}
Here's a working codesandbox.
Aside
Reserve “verb” names for methods/functions, not components. Component names should represent entities (for the most part, ex: Cart), not actions (ex: AddToCart).
3 Comments
ZebraCoder
We can use directly write this { book }: Book Why write this { book }: CartProps
Yulian
@ZebraCoder If I'm understanding, you're asking why the object containing book is set to CartProps and not Book? Because it is not true that { book } is of type Book; it is an Object containing a Book object. The bracketed object "book" is not what CartProps is type controlling; book is just one of many props that AddToCart can potentially consume (ex: { book, ASIN, timestamp }). This example was written assuming a general cart system; as in one that will include more keys in CartProps.
Yulian
@ZebraCoder you can try it out in the answer's codesandbox above for clarification. If you try to set it to Book it will throw typing errors for this reason.


<AddToCart>component is not expecting thisbookprop. We know nothing of this component.