I have a styled component like this:
export const Text = styled.div`
padding: ${props => props.theme.padding * 2};
`;
Unfortunately this doesn't work because in my scenario props.theme.padding
is 2rem (a string) and therefore cannot be multiplied with a number.
From my research I've seen a few conversations on the github page where people have requested a way to do this, but I can't find an actual clean solution anywhere. I will need to write code like this a lot. Is it possible?
You could pass the number as prop and add the unit in the styled component
export const Text = styled.div`
padding: ${props => parseFloat(props.theme.padding) * 2}rem; // padding is a float here
`;
or you should extract the number, which i dont recommend much due to performance implication
const valueFromUnit = x => parseFloat(x.match(/\d+/g));
export const Text = styled.div`
padding: ${props => valueFromUnit(props.theme.padding) * 2}rem;
`;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With