Home > Blockchain >  Type error when passing props to component
Type error when passing props to component

Time:01-11

Hello I have a type that looks like this:

type MenuItemType = { name: string; link: string };

Also an array of those types:

const menuItems: MenuItemType[] = [
    { name: "FAQ", link: "/faq" },
    { name: "Terms of use", link: "/terms" },
    { name: "Cookie policy", link: "/cookie-policy" },
    { name: "Privacy policy", link: "/privacy-policy" },
    { name: "Subscription", link: "/subscription" },
];

And a component that takes some props that are of this same type:

function ListItem({ name, link }: MenuItemType) {
    return (
        <li className="text-xs mr-14 last:mr-0">
            <Link href={link}>
                <a>{name}</a>
            </Link>
        </li>
    );
}

The ListItem Component is rendered in a map function, and this is where typescript is complaining.

enter image description here

What am i doing wrong?

CodePudding user response:

You've defined your ListItem component so it expects separate props for the name and link, not a combined prop of the item. So if ListItem is correct, you'll use it like this:

<ListItem name={item.name} link={item.link} />
// or:
<ListItem {...item} />

Alternatively, if you want to pass in a single item prop, rewrite ListItem to this:

function ListItem({ item }: { item: MenuItemType }) {
    return (
        <li className="text-xs mr-14 last:mr-0">
            <Link href={item.link}>
                <a>{item.name}</a>
            </Link>
        </li>
    );
}
  •  Tags:  
  • Related