cssreact-nativeflexboxreact-native-flexbox

react native flex 50% causes errors


I'm trying to learn react native.

I have the following code:

<View>
    <View style={{flex:0.5,flexDirection="row"}}>
        <Image source={{uri:"http://image.com/image1.jpg"}} style={{width:100,height:'auto'}} resizeMode={"cover"} />
        <Text>Picture 1</Text>
    </View>
    <View style={{flex:0.5,flexDirection="row"}}>
        <Image source={{uri:"http://image.com/image2.jpg"}} style={{width:100,height:'auto'}} resizeMode={"cover"} />
        <Text>Picture 2</Text>
    </View>
    <View style={{flex:0.5,flexDirection="row"}}>
        <Image source={{uri:"http://image.com/image3.jpg"}} style={{width:100,height:'auto'}} resizeMode={"cover"} />
        <Text>Picture 3</Text>
    </View>
    <View style={{flex:0.5,flexDirection="row"}}>
        <Image source={{uri:"http://image.com/image4.jpg"}} style={{width:100,height:'auto'}} resizeMode={"cover"} />
        <Text>Picture 4</Text>
    </View>
</View>

But this when I run this code, I get an error saying the line

<View style={{flex:0.5, flexDirection:"row"}}>

"is an unexpected token".

I tried replace 0.5 with 50% and "0.5" but those also causes error.

Basically if this were html css for the web, the behaviour I'm trying to achieve is:

<div>
    <div style="width:50%; float:left;">
        <img src="http://image.com/image1.jpg" style="width:100%; height:auto;" />
        <span>Picture 1</span>
    </div>
    <div style="width:50%; float:left;">
        <img src="http://image.com/image2.jpg" style="width:100%; height:auto;" />
        <span>Picture 1</span>
    </div>
    <div style="width:50%; float:left;">
        <img src="http://image.com/image3.jpg" style="width:100%; height:auto;" />
        <span>Picture 1</span>
    </div>
    <div style="width:50%; float:left;">
        <img src="http://image.com/image4.jpg" style="width:100%; height:auto;" />
        <span>Picture 1</span>
    </div>
</div>

In other words, I just want two columns of thumbnail images with a caption underneath each image.


Solution

  • Set up the container with flexDirection:'row' and each child to have half of the screen flexBasis without flex grow. something like this:

    <View>
    <View style={{flexDirection="row"}}>
        <Image source={{uri:"http://image.com/image1.jpg"}} style={{flexBasis:Dimensions.get('window').width / 2, flexGrow:0}} resizeMode={"cover"} />
        <Text {{flexBasis:Dimensions.get('window').width / 2, flexGrow:0}}>Picture 1</Text>
    </View>
    ...