最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Multiply value with unit in styled component - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

3 Answers 3

Reset to default 4

I 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

发布评论

评论列表(0)

  1. 暂无评论