I have a styled ponent 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?
I have a styled ponent 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?
Share Improve this question asked Jun 15, 2018 at 19:22 CaribouCodeCaribouCode 14.4k33 gold badges111 silver badges185 bronze badges3 Answers
Reset to default 4I got around this by using calc()
export const Text = styled.div`
padding: calc(${props => props.theme.padding} * 2);
`;
You could pass the number as prop and add the unit in the styled ponent
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 remend 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;
`;
I was able to acplish this with a pretty simple utility function:
// utils.js
export const unitMultiplier = (value) => (quotient) => {
const num = parseFloat(value);
const unit = value.replace(num.toString(), "");
return num * quotient + unit;
};
You could just include this in your project like so:
import { unitMultiplier } from "~/utils";
export const Text = styled.div`
padding: ${props => unitMultiplier(props.theme.padding)(2)};
`;
UPDATE: I discovered that there is a library that is really good at this sort of thing: https://polished.js/docs/#math