'Spread only relevant props to component
I have a simple component and I want it to have most (if not all) the default HTML element props, maybe extending React.HTMLAttributes<HTMLElement> and then spreading them in the component's attributes.
But the props' type also includes some non-default to be used elsewhere, let's say props.cardTitle. That prop isn't useful for the main container, but will also be included in the final HTML. I could manually exclude it when spreading the props, but there may be a lot of them.
So the question is, how can I exclude all non-default props when spreading them in the main container?
Here's an example to further illustrate this:
type Props = ParentProps & OtherProps;
type ParentProps = {
className: string,
// onClick, etc. maybe extend all html element props.
}
type OtherProps = {
cardTitle: string,
cardBody: string,
cardPrice: string,
}
export default function ProductCard(props: Props) {
return (
// Pass all props excluding "OtherProps" that have no use here
// and inside use other props normally
<div {...props}>
<p>{props.cardTitle}</p>
<p>{props.cardBody}</p>
<p>{props.cardPrice}</p>
</div>
);
}
I've been trying some unconventional ways to do it. Probably using an object inside the type with all "non-default" props, and then just excluding that one, would be my best bet. But this still has some extra syntax to call it from another component.
Since I'm both new to React and moving from JS to TS, figured it would be better to ask.
Solution 1:[1]
You can use object destructuring to strip them out.
Example
let {cardTitle, cardBody, cardPrice, ...remainingProps} = props;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | WardenUnleashed |
