Css helper component with passed in prop in TS #3983
-
|
(This is partly a TS question) I can make the component fine with the css helper but I don't know how to add them to another component. It's very easy if you don't have any props, you just I am also open to doing the same thing a different way. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
|
I can do this as a function that returns the css helper, and takes in the width as a param, but that seems like a less than ideal solution, but possibly the only one. Usage |
Beta Was this translation helpful? Give feedback.
-
|
Your approach with const WidthStyles = css<{ $width: WidthBreakpoints }>`
max-width: ${({ $width }) => formatPx($width?.sm)};
`;
const MyComponent = styled.div<{ $width: WidthBreakpoints }>`
${WidthStyles}
`;The component using the shared styles needs to declare the same prop in its generic parameter. The function-returning-css approach you mentioned also works and avoids the prop type duplication: const widthStyles = (width: WidthBreakpoints) => css`
max-width: ${formatPx(width?.sm)};
`;
const MyComponent = styled.div<{ $width: WidthBreakpoints }>`
${({ $width }) => widthStyles($width)}
`;Both are valid patterns. |
Beta Was this translation helpful? Give feedback.
Your approach with
css<{ $width: WidthBreakpoints }>is correct. The props type on thecsshelper merges with the styled component's props when used as an interpolation:The component using the shared styles needs to declare the same prop in its generic parameter. The function-returning-css approach you mentioned also works and avoids the prop type duplication: