Recently, I designed a custom Text
component that accepts several props. These props are then forwarded to the styled component where specific styles are applied. However, I am facing an issue where I do not want these props to be passed down to the DOM, but rather be accessible only within the styled component.
While converting props to transient props is a solution, it leads to repetitive code which unnecessarily increases the size of the component. Is there a way to pass certain props to the styled component without having them propagate to the DOM, and without having to redefine each prop individually? I experimented with using shouldForwardProps
, but unfortunately, I encountered difficulties integrating it 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>
);
};