Home > Blockchain >  React Native, How to flexibly size picture within flexGrow?
React Native, How to flexibly size picture within flexGrow?

Time:12-26

I have several Views and after those, I want to use the remaining space on the screen for a flexible preview gallery. However, as of now, I can only make the picture take the natural picture size, it does not resize to its flexbox bounds. Here's the outer App.tsx:

return (
    <View style={[styles.wrapper, { backgroundColor: 'blue' }]}>
        // lots of components
        <View style={[styles.previewContainer, { backgroundColor: 'yellow' }]}>
            <Preview/>
        </View>
    </View>
)

Here the associated style allocating the remaining space to the previewContainer:

const styles = StyleSheet.create({
    wrapper: {
        backgroundColor: COLORS.backgroundLight,
        flex: 1,
    },
// other irrelevant styles...
    previewContainer: {
        flexGrow: 1,
        marginTop: 8,
        marginHorizontal: 12,
        margin: 8,
    },

});

And here's the Preview component which basically just ignores its container bounds set in the App.tsx. Preview.tsx:

// example assets to exclude prop passing as an error source
const assets = [
    require('../images/ex1.png'),
    require('../images/ex2.png'),
    require('../images/ex3.png'),
    require('../images/ex4.png'),
]

export const Preview = (images: any) => {

    const [pictures, setPictures] = useState(assets)
    return (
        <View style={styles.previewRow}>
            <View style={styles.previewCell}>
                <Image
                    // do I need a style here?
                    source={assets[0]}
                    resizeMode='cover'
                />
            </View>

        </View>
    )


}
const styles = StyleSheet.create({
    previewRow: {
        flexDirection: 'row',
    },
    previewCell: {
        //what am I supposed to do here?
    }

})

Later, I'd like for up to 4 pictures to be displayed in a grid-like gallery. However, for now, it's important that the allocated remaining space is used and the picture is scaled accordingly.

CodePudding user response:

Specify the dimensions of images. One way to do it for 2x2 grid:

<View style={{ flex: 1} }>
  <Text>Hello World!</Text>
  <View style={{ backgroundColor: "red", height: 30 }} />
  <View style={{ backgroundColor: "green", height: 100 }} />
  <View style={{ backgroundColor: "blue", height: 20 }} />
  <View style={{ flexDirection: "row", flexWrap: "wrap", flexGrow: 1 }}>
    <Image
      style={{width: "50%"}}
      source={{uri: 'https://reactnative.dev/img/tiny_logo.png'}}/>
    <Image
      style={{width: "50%"}}
      source={{uri: 'https://reactnative.dev/img/tiny_logo.png'}}/>
    <Image
      style={{width: "50%"}}
      source={{uri: 'https://reactnative.dev/img/tiny_logo.png'}}/>
    <Image
      style={{width: "50%"}}
      source={{uri: 'https://reactnative.dev/img/tiny_logo.png'}}/>
  </View>
</View>
  • Related