Search code examples
reactjsreact-propsreact-typescript

Giving error when sending props in react typescript


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

enter image description here enter image description here


Solution

  • 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).