How do I pass properties…
How do I pass properties as an object that is spread on the component? For example, I have <Item {...item} key={index} />
which is being mapped. I get an error that one of my required props url
is not being passed, even though it is inside of the item
object which is being spread.
Essentially this is what is being spread and url
is the only required prop that I have on it right now
item = { text: "Home", url: "/" };
Responses:
Your code is correct, I suspect your item is not what you think it is
Also, key being index is useless
why is key useless? it’s supposed to be a unique number right?
Here is a broader view of my code
Header Component ``` const NavItems = [ { active: true, text: ‘Home’, url: ‘/’, }, { text: ‘Page 2’, url: ‘/page-2’, }, ];
<Navigation items={NavItems} />
*Navigation Component*
export const Navigation = ({
direction = ‘vertical’,
items,
}: NavigationProps) => {
return (
<nav>
<ul className={direction}>
{items.map((item, index) => {
return <Item {…item} key={index} />;
})}
</ul>
</nav>
);
};
*Item Component*
export const Item = ({
active = false,
altText,
direction = ‘vertical’,
onClick,
icon,
iconClasses,
iconPlacement = ‘left’,
itemClasses,
text,
textClasses,
url = ‘’,
}: NavigationItemProps) => {
return (
<li className={${itemClasses} ${direction} ${active ? 'active' : ''}
}>
<Link
to={url}
title={text}
onClick={(event) => onClick && onClick(event)}
>
{icon && (
<img
alt={altText || text}
className={${iconClasses} ${iconPlacement}
}
src={icon}
/>
)}
{text && <span className={textClasses}>{text}</span>}
</Link>
</li>
);
};```
If you use index as a key, it gives react no extra info to use when determining if this is the same competent as was in the last loop.
Use something unique about item, I’m this case, url would probably do
Can you post your prop types?
export interface NavigationItemProps {
active?: boolean;
altText?: string;
direction?: 'horizontal' | 'vertical';
icon?: string;
iconClasses?: string;
iconPlacement?: 'left' | 'right';
itemClasses?: string;
onClick?: (event: MouseEvent) => void;
text?: string;
textClasses?: string;
url: string;
}
As for the key, thanks that makes sense
Are you sure it’s Item that is throwing the proptype error? Not link?
Otherwise, this seems fine to me
Yeah, that’s why it’s throwing me too. I figure maybe TS doesn’t know how to look into the item
?
Try doing it mantually
<Item url="test" {...item} />
whats your props interface for Navigation Component
?
Figured it out, I had to specify the object for item
{items.map((item: NavigationItemProps, index: number) => {