Styled Component — refactor to css with props in TypeScript

Fred Wong
fredwong-it
Published in
1 min readJul 27, 2022

--

I have this code currently in my PR and my teammate left comment that we can refactor this to re-use style with css.

Original code

const StyledAppleIcon = styled(ApplenIcon)<{
$width: number,
$height: number,
$color: string
}>`
width: ${({ $width }) => $width}px;
height: ${({ $height }) => $height}px;
color: ${({ $color }) => $color};
`;
const StyledOrangeIcon = styled(OrangeIcon)<{
$width: number,
$height: number,
$color: string
}>`
width: ${({ $width }) => $width}px;
height: ${({ $height }) => $height}px;
color: ${({ $color }) => $color};
`;

Now refactor to

const fruitStyle= css<{
$width: number,
$height: number,
$color: string
}>`
width: ${({ $width }) => $width}px;
height: ${({ $height }) => $height}px;
color: ${({ $color }) => $color};
`;

const StyledAppleIcon = styled(AppleIcon)`
${fruitStyle}
`;
const StyledOrangeIcon = styled(OrangeIcon)`
${fruitStyle}
`;

Reference:

--

--