Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply value with unit in styled component

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?

like image 371
CaribouCode Avatar asked Jun 15 '18 19:06

CaribouCode


Video Answer


1 Answers

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;
`;
like image 187
johnny peter Avatar answered Sep 18 '22 07:09

johnny peter