5

I want to render 7 buttons in a row with equal width to fill up all the available space horizontally.

render() {
    return (
        <FlatList
            data={this.state.days}
            renderItem={({ item }) => <View style={styles.button}><Button title={item.getDate().toString()} /></View>}
            keyExtractor={item => item.getDate().toString()}
            horizontal={true}
            style={styles.list}
        />
    );
}

const styles = StyleSheet.create({
    list: {
        display: 'flex'
    },
    button: {
        flex: 1
    }
});

They are inside a flatlist, wrapped in a view because I cannot style buttons directly. In regular flexbox in an HTML page this approach works.

This what I get in React Native:

enter image description here

Maybe there are some flatlist behaviour I'm not familiar with?

benomatis
  • 5,536
  • 7
  • 36
  • 59
marchello
  • 2,016
  • 3
  • 29
  • 39

5 Answers5

6

First of all when you are styling in react native everything is already in flex so you don't have to do display : flex

If you want to render 7 buttons with the same width in a row make sure that all of them have the same parent. Then use flex:1 in each one of them.

What is happening when you do flex:1 when you put a number in front of flex in your styles in this particular situation it divides your parent into those many parts and give it to the child.

So all your button will have 1/7th of the width. If you put flex:2 in one of the styles then that button will have 2/7th of the width and the rest will have 1/7th.

Please feel free to ask for more clarity on the above said.

Yash Kalwani
  • 443
  • 4
  • 11
  • Yes I understand what `flex: 1` does. So, in my case it should give the the `` elements 1/7th of the width. But it does not. Maybe Flatlist is not the direct parent of the `` elements ? – marchello Mar 23 '18 at 09:37
6

I got the same issue, I have added View component cover for each Button like the code below:

<View style={{flexDirection:"row"}}>
    <View  style={{flex:1}}>
        <Button title="Add"  />
    </View>
    <View  style={{flex:1}}>
        <Button title="Clear"  />
    </View>
    //....
</View>
benomatis
  • 5,536
  • 7
  • 36
  • 59
Albert Pham
  • 153
  • 1
  • 8
0

Have you tried adding flex: 1 to the list so that it takes up the entire horizontal space?

alberta
  • 225
  • 2
  • 7
0

in my point of view, try adding justifyContent as space-between in the style object list

Harikrishnan S
  • 124
  • 2
  • 13
0

in each item ,set this style:

width:width/7