Search code examples
react-nativescrollview

How to make ScrollView only scroll when child size is larger in React Native


How are you.

I would like to make component that has fixed height.

it's wrapped by ScrollView and I want this scrollview don't scroll if child height is small than fixed height.

Is that possible?

Thanks


Solution

  • You could render a normal View or a ScrollView based on some condition, consider this example:

    class MyComponent extends React.Component {
      constructor(props){
        super(props)
        this.state = {
          childHeight: 0,
          screenHeight: Dimensions.get('window').height
        }
      }
      render(){
        const wrapper = this.state.childHeight > this.state.screenHeight ? ScrollView : View 
        return (
          <Wrapper>
            //onLayout passes a an object with a synthetic event that has a nativeEvent prop
            //I pull off the nativeEvent prop using deconstruction so I can get the height
            <View onLayout={
              ({ nativeEvent }) => {
                this.setState({ childHeight: nativeEvent.layout.height })
              }}>
            {children}
            </View>
          </Wrapper>
        )
      }
    }
    

    This is just one implementation, you could do it however you like. Here's some more info on the onLayout prop.

    If you can't or don't want to use a View then you would have to do some other sort of layout calculation. One way is by manipulating your styles and the children prop:

    const myStyle = StyleSheet.create({
      childStyle: {
        height: 180 
      }
    })
    
    class MyComponent extends React.Component {
      constructor(props){
        super(props)
        this.state = {
          childHeight: React.Children.count(props.children) * 180, 
          //get the count of how many children have been passed to your component
          //and multiple it by whatever height your children have set in their styles
          screenHeight: Dimensions.get('window').height 
      }
      render(){
        const wrapper = this.state.childHeight > this.state.screenHeight ? ScrollView : View
        return (
          <Wrapper>
            {children}
          </Wrapper>
        )
      }
    }
    

    If the number of children can change throughout multiple renders then I would suggest learning about the FlatList component