1

I'm trying to display images with round borders in a FlatList. However, I'm using flex, so I don't know the absolute value to put in borderRadius. This is what I tried:

function Row(obj) {
    const [width, setWidth] = useState(0);

    return (
        <View style={styles.contact}>
            <Image
                style={[styles.thumbnail, {borderRadius: width / 2}]}
                onLayout={({nativeEvent}) => {setWidth(nativeEvent.layout.width);}}
                source={{uri: obj.picture.thumbnail}}
            />
            <View style={styles.contactInfo}>
                <Text>{obj.name}</Text>
                <Text>{obj.phone}</Text>
            </View>
        </View>
    );
}

export default function Contacts() {
    <View style={styles.contactsContainer}>
        <FlatList
            data={contacts}
            renderItem={({ item }) => Row(item)}
            keyExtractor={item => item.id.toString()}
        />
    </View>
}

It doesn't work because Hooks can only be called inside the body of a functional component.

Any idea?

1 Answers1

0

I would try wrapping this Image component into a View and add the borderRadius attribute on the View's style, together with a overflow: 'hidden'. This way you're making sure that the image is in fact inside of a component with the border radius you want.

Something similar to this:

return (
        <View style={styles.contact}>
          <View style={[styles.thumbnail, {borderRadius: width / 2, overflow: 'hidden'}]}>
            <Image
                style={{flex: 1}}
                onLayout={({nativeEvent}) => {setWidth(nativeEvent.layout.width);}}
                source={{uri: obj.picture.thumbnail}}
            />
            <View style={styles.contactInfo}>
                <Text>{obj.name}</Text>
                <Text>{obj.phone}</Text>
            </View>
        </View>
    );

Then in order to determine how big your borderRadius should be, you can extract the device's width or height by using Dimensions from react-native (and the apply the transformation you find useful for it)

an example:

import {Dimensions} from 'react-native'
let width = Dimensions.get('window').width
Gabcvit
  • 1,468
  • 1
  • 15
  • 32