'Define variables in styled-components

Is it possible to define a variable inside a styled-components component?

Hopefully the code below (not working) shows what I'm after:

const Example = styled.div`
  ${const length = calc(vw - props.someValue)}

  width: ${length};
  &.disable {
    width: ${length};
  }  
`


Solution 1:[1]

This code will not work, as far as I understand Template Literal's guidelines.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Template literals are those backticks that wraps the code you have after the div .

const Example = styled.div`here`

Let's say:

const num = 10;
console.log(\`The number I saved in a variable is ${num}\`);

The output log would be: "The number I saved in a variable is 10"

Inside Template literals you can have an expressions. Declaring a variable is not possible inside because its a statement: http://2ality.com/2012/09/expressions-vs-statements.html

So this question is more about the core of Javascript then styled-components in itself.

Solution 2:[2]

A possible workaround using CSS variables but no ie support.

const Example = styled.div`
  --length: calc(vw - props.someValue)

  width: calc(var(--length));
  &.disable {
    width: calc(var(--length));
  }  
`

Solution 3:[3]

I recently wanted to do something like this. But in my case, I had to compute new var with the use of props only and not with vw.

I achieved this by defining a short function.

const getLength = (baseValue, someValue) => {
   // you can do any complex or multiline calculation here
   return baseValue - someValue;
}

const Example = styled.div`
width: ${(props) => getLength(props.baseValue, props.someValue)};
&.disable {
width: ${(props) => getLength(props.baseValue, props.someValue)};
}  
`

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 harry
Solution 3 djsdev