four-eyes
four-eyes

Reputation: 12439

Use percentage/relative values in Styling of <View /> on iOS in react-native

I want to do something like this in react-native

<View
    style = { width: '100%', padding: 10, borderRadius: '25%' }> 
    {...}
</View>

But I get (on iOS)

JSON value '25%' of type NSString cannot be converted to NSNumber

Is there a way to use relative/percentage values as styling input for borderRadius?

Upvotes: 2

Views: 667

Answers (2)

Leri Gogsadze
Leri Gogsadze

Reputation: 3093

You can do something like that, use ref in order to have a reference to that element, then you can measure its width (not in percentage) and you can calculate the border radius.

import React, { useRef, useEffect, useState } from 'react';
import { Text, View, StyleSheet } from 'react-native';

export default function App() {
  const ref = useRef();

  const [width, setWidth] = useState(0);

  useEffect(() => {
    ref.current.measure((x, y, w, h) => {
      setWidth(w);
    });
  }, []);

  return (
    <View style={styles.container}>
      <View
        ref={ref}
        style={{
          width: '80%',
          padding: 10,
          backgroundColor: 'red',
          borderRadius: width / 4, // 25%
        }}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

Upvotes: 2

Quang Th&#225;i
Quang Th&#225;i

Reputation: 697

Okay, after a quick researching, i found that borderRadius style expects number as a value, not a String

So if you want to custom the value of borderRadius, you can do sth like this:

<View style={{
  width: 300,
  height: 300,
  backgroundColor: 'red',
  padding: 10,
  borderRadius: 300/4     // equal 25% of its size 
}}>

Upvotes: 0

Related Questions