I have created a Text
component which receives couple of props. These props are passed to the styled component, where styles are applied. I dont want to pass props to the DOM, I only want to access them inside styled component.
Converting props to transient props works, but it creates repeating code which I think makes the whole component unnecessarily bigger.
I would like to know, how to pass some props to my styled component without passing them to the DOM and without having to redefine every prop. I tried using shouldForwardProps
but I cant get it to work with Typescript.
type Props = {
children: React.ReactNode;
size: number;
height: number;
color: string;
};
const StyledText = styled.p<{ $color: string; $size: number; $height: number }>`
color: ${({ $color }) => $color};
font-size: ${({ $size }) => `${$size}px;`};
line-height: ${({ $height }) => `${$height}px;`};
...
`;
const Text: React.FC<Props & React.HTMLAttributes<HTMLParagraphElement>> = ({ children, size, height, color, ...rest }) => {
return (
<StyledText $size={size} $height={height} $color={color} {...rest}>
{children}
</StyledText>
);
};
2
Answers
What you should thrive for is having a default StyledText component and then override this component using the
styled
functionand then you override it like this
Usually in a design system, you define the different variants of your text/typography. It is limited (ie: heading, subheading, text). Therefore it is better to have different components like this than influencing the final user to pass variables that risk not to comply with the design you imagined
Here is a solution using
shouldForwardProps
as you suggested which I believe is what you are asking for. I’ve tried to tie in thecustomAttributeNames
to theProps
, but I’ve given up on that.Here is a sandbox so you can see it working.