learningtech
learningtech

Reputation: 33715

react-native scrollview does now respect flex?

I'm learning flex layout for react native. This is my code:

import React, { Component } from 'react';

import {
  Text,
  View,
  ScrollView
} from 'react-native';

const style = {
  container: {
    flex:1,
    flexDirection:'column',
    flexWrap:'nowrap',
    alignItems:'stretch',
  },
  title: {
    flex:1,
    backgroundColor:'blue',
  },
  terms: {
    flex:8,
    flexDirection:'column',
    backgroundColor:'red',
  },
  termsText: {
    padding:15,
    flex:1,
  },
  check: {
    flex:1,
    backgroundColor:'yellow',
  }
};


export default class Home extends Component {

    constructor(props)
    {
        super(props);
    }

  render() {

    return (

        <View style={style.container}>
            <Text style={style.title}>Terms and Conditions</Text>
            <ScrollView style={style.terms}>
            <Text style={style.termsText}>You must comply, or die...</Text>
            </ScrollView>
            <Text style={style.check}>Check mark here (tap to agree to terms)</Text>
        </View>

    );

  }
}

And the result is this:

enter image description here

This is not what I expected. I was expecting the red area to take up 80% of the vertical height because style.terms.flex == 8. If I changed the contents of my render to this:

  render() {

    return (

        <View style={style.container}>
            <Text style={style.title}>Terms and Conditions</Text>
            <Text style={style.terms}>You must comply, or die...</Text>
            <Text style={style.check}>Check mark here (tap to agree to terms)</Text>
        </View>

    );

  }

I am then able to get the red area to become 80% vertical height. Why does ScrollView not respect style.terms.flex?

Upvotes: 0

Views: 299

Answers (2)

JainZz
JainZz

Reputation: 612

Use Dimensions Api for ScrollView

const { width, height } = Dimensions.get('window');

<ScrollView style={{ height: height * 0.8 }}>
    <Text style={style.termsText}>You must comply, or die...</Text> 
</ScrollView>

height * 0.8 get the 80 percentage of height with respect to the screen size

Upvotes: 1

Nemi Shah
Nemi Shah

Reputation: 876

"Keep in mind that ScrollViews must have a bounded height in order to work, since they contain unbounded-height children into a bounded container (via a scroll interaction)." From the react native docs. What you can do is use the Dimensions API of react native and give the ScrollView 80% of device height instead.

More on ScrollView

Dimensions

Upvotes: 2

Related Questions