3

I'm using styled-components in react-native with the calc() function

const MyElement = styled(MyText)`
    position: absolute;
    left: calc(20% - 10px);
`

Error

JSON value 'calc(20% - 10px)' of type NSString cannot be converted to YGValue. Did you forget the % or pt suffix?

I already found this solution (CSS' calc() in styled-components). But I am already using whitespaces.

What am I doing wrong?

1 Answers1

5

React-native uses yoga layout which doesn't support calc. Ideally try to position your elements using flex. Otherwise, create additional wrapper for the element, go with left: 20% on on it and add -10px on the element itself. Another option is to calculate left yourself from container width using View#onLayout of that container. It is also possible to calculate it from screen width (if your element can be positioned based on screen width rather than parent width) with Dimensions

Max
  • 4,473
  • 1
  • 16
  • 18
  • Ok, but [here](https://stackoverflow.com/questions/65135806/using-styled-components-on-react-native-how-can-i-calc-the-height-of-a-componen) they state that it can be used with react-native. In any case, thanks for the suggestions on how to do it without calc()! Much appreciated – Julian Haluska Mar 01 '21 at 12:00
  • 1
    Pretty sure that answer might not be correct, you could try and see that, for example, `calc(100%)` doesn't work, as well as units like `vh` and `vw` @jayhaluska – Max Mar 01 '21 at 14:04